题目描述
https://leetcode-cn.com/problems/subarray-sum-equals-k/
思路题解
https://leetcode-cn.com/problems/subarray-sum-equals-k/solution/he-wei-kde-zi-shu-zu-by-leetcode-solution/
前缀和和枚举的题解在上方,前缀和代码在下方:
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
pre = 0
count = 0
dic = {0:1}
for i in nums:
pre += i
if (pre-k) in dic:
count += dic[pre-k]
dic[pre] = dic.get(pre,0) + 1
return count
原来的思路:滑动窗口,后来发现可以是负的。后来又想dp,又觉得比较复杂,遂放弃。
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
#sum<k right++
#sum>k left++
#sum==k left++ 防止1,1,1 k=2的情况遗漏
left,right,sum,ans=0,0,nums[0],0
while right<len(nums) and left<len(nums):
print(left,right,sum,ans)
if sum<k:
right+=1
if right<len(nums):
sum+=nums[right]
if sum>k and left+1<len(nums):
sum-=nums[left]
left+=1
if sum==k:
sum-=nums[left]
left+=1
ans+=1
if right==left and right==len(nums)-1:
break
return ans