560. Subarray Sum Equals K(题目链接)
Medium
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
Constraints:
- The length of the array is in range [1, 20,000].
- The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
方法1:暴力搜索,但是没有过,超时
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
rlt = 0
for i in range(len(nums)):
sum = 0
for j in range(i, len(nums)):
sum += nums[j]
if sum == k:
rlt += 1
return rlt
方法2:
参考https://www.cnblogs.com/grandyang/p/6810361.html
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
d = collections.defaultdict(int)
sum1 = 0
rlt = 0
d[0] = 1
for i in range(len(nums)):
sum1 += nums[i]
rlt += d[sum1 - k]
d[sum1] += 1
return rlt