实验一

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

    }

}

posted @ 2017-03-06 19:54  Reversal-destiny  阅读(134)  评论(0编辑  收藏  举报