Subarray Sum Equals K

这里还是强调两点:

  1. 前缀和加哈希表的组合,每次哈希表起始最好放一个0为key的键值对,可以避免很多问题
  2. 前缀和加好之后,先检查之前的key,再把新的前缀和加进去可以避免错误
class Solution(object):
    def subarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        store = collections.Counter({0:1})
        tmp = 0
        result = 0
        for num in nums:
            tmp += num
            if tmp - k in store:
                result += store[tmp - k]
            store[tmp] += 1
        return result

results matching ""

    No results matching ""