1. 程式人生 > >LeetCode 560. Subarray Sum Equals K (和為K的子陣列)

LeetCode 560. Subarray Sum Equals K (和為K的子陣列)

原題

Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

Example 1:

Input:nums = [1,1,1], k = 2
Output: 2

Note:

  1. The length of the array is in range [1, 20,000].
  2. The range of numbers in the array is [-1000, 1000] and the range of the integer k
    is [-1e7, 1e7].

Reference Answer

Method one

看了陣列的長度,明顯O(n^2)的時間複雜度會超時。這個時間複雜度一般只能用O(N)的解法了。

使用一個字典儲存陣列某個位置之前的陣列和,然後遍歷陣列求和,這樣當我們求到一個位置的和的時候,向前找sum-k是否在陣列中,如果在的話,更新結果為之前的結果+1。同時,當前這個sum出現的次數就多了一次。

這個題的解法不難想出來,因為如果要降低時間複雜度,應該能想到增加空間複雜度,那麼要麼使用陣列,要麼就是用字典之類的,保留之前的結果。

時間複雜度是O(N),空間複雜度是O(N).

自己實現了一種O(n^2)的做法,時間複雜度太高,超時。參考答案最巧妙之處在於記錄所有可能出現值的次數,而對於和為k的次數,只需要滿足 if (sum - k) in d: res += d[sum - k] 即可求出所有可能次數。說白了就是用空間換時間,不過方法確實很巧妙!要注意學習!!!

Code

class Solution:
    def subarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
n = len(nums) d = collections.defaultdict(int) d[0] = 1 sum = 0 res = 0 for i in range(n): sum += nums[i] if sum - k in d: res += d[sum - k] d[sum] += 1 return res

Note

  • 參考答案最巧妙之處在於記錄所有可能出現值的次數,而對於和為k的次數,只需要滿足 if (sum - k) in d: res += d[sum - k] 即可求出所有可能次數。說白了就是用空間換時間,不過方法確實很巧妙!要注意學習!!!
  • 注意 d = collections.defaultdict(int) 的使用,直接呼叫 collections.defaultdic(int) 使得預設預設key的value為0;
  • 這裡初始值賦值為 d[0] = 1,也可以算是動態規劃+dict的預設初試配置了。

參考文獻

[1] https://blog.csdn.net/fuxuemingzhu/article/details/82767119