1. 程式人生 > >LeetCode(Top Interview Questions)——Array

LeetCode(Top Interview Questions)——Array

(一)Remove Duplicates from Sorted Array

 Given a sorted array nums, remove the duplicates in-place such that each
  element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying
 the input array in-place with O(1) extra memory.
  • 要求:剔除有序陣列中的重複值。

  • 思想:將已經去重的元素儲存在陣列的前半部分。遍歷後續的每一個元素並與已去重部分的最大元素比較,如果相等則無操作繼續遍歷,如果不等則將此元素儲存在已去重部分。

  • code:

public int removeDuplicates(int[] nums) {
        int length=1;
        for(int i=1;i<nums.length;i++){
            if (nums[i]!=nums[length-1]){
                nums[length]=nums[i];
                length++
; } } return length; }
  • 如果陣列是無序的,則需與已去重部分逐一比較。這個效率較低。
public int removeDuplicates(int[] nums) {
        int length=1;
        for(int i=1;i<nums.length;i++){
            for(int j=0;j<length;j++){
                if (nums[i]==nums[j]) break;
                else
if (j==length-1) { nums[length]=nums[i];length++; } } } return length; }

(二)Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock
 on day i.

Design an algorithm to find the maximum profit. You may complete as many 
transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you 
must sell the stock before you buy again).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
             Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.
Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
  • 要求:陣列值為股票價格,下標對應日期,股票可以多次買賣,但不可以同一天既買又賣。找出最大利潤。
  • 思想:因為可以多次買賣,所以找出相鄰股票價格的最大上升趨勢,這便是一次合適的買賣。
  • code
 public int maxProfit(int[] prices) {
        int total=0;
        for (int i=0;i<prices.length-1;i++) {
            if (prices[i+1]>prices[i]) total+=prices[i+1]-prices[i];
        }
        return total;
    }
  • 這是效率最高的程式碼,有人說這違反了題目中不能同一天買賣的要求,其實可以理解為每天都計算一次當日利潤,盈利則算在總收入之中,虧損則無操作,相當於昨天已經賣掉。然後繼續等待下一次盈利時計算利潤,就假裝是買入了。
  • 如果非要較真的話,也可以嘗試這個解決方案:
public int maxProfit(int[] prices) {
    int profit = 0, i = 0;
    while (i < prices.length) {
        // find next local minimum
        while (i < prices.length-1 && prices[i+1] <= prices[i]) i++;
        int min = prices[i++]; // need increment to avoid infinite loop for "[1]"
        // find next local maximum
        while (i < prices.length-1 && prices[i+1] >= prices[i]) i++;
        profit += i < prices.length ? prices[i++] - min : 0;
    }
    return profit;
}