Topic 1

1. Given a sorted array, you need to remove duplicate elements in place so that each element appears only once, and return the new length of the removed array. Instead of using extra array space, you have to modify the input array in-place and do it with O(1) extra space.

给定数组 nums = [1,1,2], 

函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 

你不需要考虑数组中超出新长度后面的元素
class Solution{
    public int removeDuplicates(int[] nums){
        int len = nums.length;
        if(len == 0){
            return 0;
        }
        int j = 0;
        for(int i = 0 ; i < len ; i++){
            if(nums[i] != nums[j]){
                nums[++j] = nums[i];
            }

        }
        return ++j;
    }
}

2. Given an array whose ith element is the price of a given stock on the ith day.

Design an algorithm to calculate the maximum profit you can make. You can complete as many trades as you can (buying and selling a stock multiple times).

Note: You cannot participate in multiple trades at the same time (you must sell the previous shares before buying again).

输入: [7,1,5,3,6,4]
输出: 7
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
     随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。
class Solution{
    public int maxprofit(int[] prices){
        int len = prices.length;
        if(len == 0){
            return 0;
        }
        int max = 0;
        int d = 0;
        for(int i = 1 ; i < len ; i++){
            d = prices[i] - prices[i-1];
            if( d > 0)
                max += d;
        }
        return max;
    } 
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324730486&siteId=291194637