zoukankan      html  css  js  c++  java
  • 实验一

    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];

        }

    }

  • 相关阅读:
    vim删除操作
    kubectl命令自动补全
    kubelet资源限制
    一道c语言运算符优先级问题
    c语言自加自减三道题
    C语言操作符优先级
    [word]2010中插入公式自动编号并且公式不自动缩小/变小
    [matlab]改变矩阵的大小并保存到txt文件
    dxut.h(29): fatal error C1083: Cannot open include file: 'dxsdkver.h': No such file or directory
    [vim]的关键字补全
  • 原文地址:https://www.cnblogs.com/mkyz/p/6511617.html
Copyright © 2011-2022 走看看