1. 程式人生 > 其它 >[LeetCode] 560.Subarray Sum Equals K_Medium tag: Array, Subarray, prefix Sum

[LeetCode] 560.Subarray Sum Equals K_Medium tag: Array, Subarray, prefix Sum

Given an array of integersnumsand an integerk, returnthe total number of continuous subarrays whose sum equals tok.

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= nums.length <= 2 * 104
  • -1000 <= nums[i] <= 1000
  • -107<= k <= 107

Ideas:

1. brute force T: O(n ^2), S: O(1)

class Solution:
    def subarraySum(self, nums: List[int], target: int) -> int:
        n, count = len(nums), 0
        for i in range(n):
            for j in range(i, n):
                curSum = sum(nums[i: j + 1])
                if curSum == target:
                    count 
+= 1 return count

2. 參考Prefix Sum & Dictionary Time and Space O(n) for -- Find a number of continuous subarrays/submatrices/tree paths that sum to target T: O(n), S: O(n)

class Solution:
    def subarraySum(self, nums: List[int], target: int) -> int:
        count, curSum, d = 0, 0, collections.Counter()
        
for num in nums: curSum += num if curSum == target: count += 1 count += d[curSum - target] d[curSum] += 1 return count