1. 程式人生 > >325. Maximum Size Subarray Sum Equals k 和等於k的最長子數組

325. Maximum Size Subarray Sum Equals k 和等於k的最長子數組

length ++ can solution image with number OS bug

[抄題]:

Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn‘t one, return 0 instead.

Note:
The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range.

Example 1:

Given nums = [1, -1, 5, -2, 3], k = 3,
return 4. (because the subarray [1, -1, 5, -2]

sums to 3 and is the longest)

Example 2:

Given nums = [-2, -1, 2, 1], k = 1,
return 2. (because the subarray [-1, 2] sums to 1 and is the longest)

Follow Up:
Can you do it in O(n) time?

[暴力解法]:

時間分析:

空間分析:

[優化後]:

時間分析:

空間分析:

[奇葩輸出條件]:

[奇葩corner case]:

[思維問題]:

以為只有max(max, a)才能取最長,不知道怎麽寫。其實就是一般思路 sum隨著i增加而變長,把i給for一遍就行了。

[一句話思路]:

gap中一下子增加了k時,index也取對應值即可

[輸入量]:空: 正常情況:特大:特小:程序裏處理到的特殊情況:異常情況(不合法不合理的輸入):

[畫圖]:

技術分享圖片

[一刷]:

  1. map.containsKey(sum)沒用,必須要sum == k才行

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分鐘肉眼debug的結果]:

[總結]:

必須考慮中間的gap. gap中一下子增加了k時,index也取對應值即可

[復雜度]:Time complexity: O(n) Space complexity: O(n)

[英文數據結構或算法,為什麽不用別的數據結構或算法]:

常量sum才能累加,數組不能:

sum[i] += nums[i]; 相當於每個數都重新加了

[算法思想:遞歸/分治/貪心]:

[關鍵模板化代碼]:

[其他解法]:

[Follow Up]:

[LC給出的題目變變變]:

2 sum: hashmap

[代碼風格] :

技術分享圖片
class Solution {
    public int maxSubArrayLen(int[] nums, int k) {
        //cc
        if (nums == null || nums.length == 0) return 0;
        
        //ini: hashmap, max
        HashMap<Integer, Integer> map = new HashMap<>();
        int max = 0, sum = 0;
        
        //for loop: 3 conditions
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            //contains, gap, not contains
            if (sum == k) max = i + 1;
            else if (map.containsKey(sum - k)) max = Math.max(max, i - map.get(sum - k));
            
            if (!map.containsKey(sum)) map.put(sum, i);
        }
        
        return max;
    }
}
View Code

325. Maximum Size Subarray Sum Equals k 和等於k的最長子數組