LeetCode560 和为 K 的子数组
前缀和 + 哈希
class Solution: def subarraySum(self, nums: List[int], k: int) -> int: pre_count, pre, ans = {}, 0, 0 pre_count[0] = 1 for c in nums: pre += c if (pre - k) in pre_count: ans += pre_count[pre - k] if pre in pre_count: pre_count[pre] += 1 else: pre_count[pre] = 1 return ans