• 实验一


    1、删除排序数组中的重复数字

    描述:给定一个排序数组,在原数组中删除重复出现的数字,使得每个元素只出现一次,并且返回新的数组的长度。

    不要使用额外的数组空间,必须在原地没有额外空间的条件下完成。

    样例

    给出数组A =[1,1,2],你的函数应该返回长度2,此时A=[1,2]。

    代码:

    public class Solution {

        /**

         * @param A: a array of integers

         * @return : return an integer

         */

        public int removeDuplicates(int[] nums) {

            // write your code here

            int i,j,l=nums.length;

                       for(i=0;i<l-1;i++){

                               

                                if(nums[i]==nums[i+1])

                                {

                                         for(j=i;j<l-1;j++)

                                         {        nums[j]=nums[j+1];

                                         }

                                         l--;

                       i--;

                                }       

                               

             }

             return l;

        }

    }

    2、买卖股票的最佳时机

    描述:假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。

    样例

    给出一个数组样例 [3,2,3,1,2], 返回 1

    代码:

    public class Solution {

        /**

         * @param prices: Given an integer array

         * @return: Maximum profit

         */

        public int maxProfit(int[] prices) {

            // write your code here

             int profit = 0;

             if( prices == null || prices.length == 0)

                return 0;

            int minbuy = prices[0];

            for(int i = 1;i< prices.length ;i++){

               

                profit= Math.max(profit,prices[i] - minbuy);

                minbuy = Math.min(minbuy,prices[i]);

            }

            return profit;

        }

    }

    3、爬楼梯

    描述:假设你正在爬楼梯,需要n步你才能到达顶部。但每次你只能爬一步或者两步,你能有多少种不同的方法爬到楼顶部?

    样例

    比如n=3,1+1+1=1+2=2+1=3,共有3中不同的方法

    返回 3

    代码:

    public class Solution {

        /**

         * @param n: An integer

         * @return: An integer

         */

        public int climbStairs(int n) {

            // write your code here

             if(n == 0)

             {

                return 1;

             }

          

             int[] a= new int[n+1];  

             a[0] = 1;

             a[1] = 1;

            

             for(int i=2;i<=n;i++){

                 a[i] = a[i-2] + a[i-1];

             }

                      return a[n];

        }

    }

  • 相关阅读:
    两步验证杀手锏:Java 接入 Google 身份验证器实战
    涨姿势:Spring Boot 2.x 启动全过程源码分析
    Spring Cloud 升级最新 Finchley 版本,踩了所有的坑!
    Spring Boot 2.x 启动全过程源码分析(上)入口类剖析
    推荐:7 月份值得一看的 Java 技术干货!
    屌炸天,Oracle 发布了一个全栈虚拟机 GraalVM,支持 Python!
    Spring Boot 核心配置文件 bootstrap & application 详解。
    出场率比较高的一道多线程安全面试题
    凉凉了,Eureka 2.x 停止维护,Spring Cloud 何去何从?
    读写Excel
  • 原文地址:https://www.cnblogs.com/mkyz/p/6511617.html
Copyright © 2020-2023  润新知