[LeetCode] 560.Subarray Sum Equals K_Medium tag: Array, Subarray, prefix Sum
2021-06-18 20:36 Johnson_强生仔仔 阅读(33) 评论(0) 编辑 收藏 举报Given an array of integers nums
and an integer k
, return the total number of continuous subarrays whose sum equals to k
.
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