560. Subarray Sum Equals K

Description:
Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

Solution:

  1. 暴力列举所有可能的子连续序列和
  2. 计算前n个序列的和,并储存与map中,再根据nums[0:i] - nums[0:j]的值来计算nums[j:i]的和
class Solution(object):
    def subarraySum(self, nums, k):
        sums, cnt, dict1 = 0, 0, {0:1}
        for i in nums:
            sums += i
            if dict1.get(sums - k) != None:
                cnt += dict1[sums - k]
            dict1[sums] = 1 if dict1.get(sums) == None else dict1[sums] + 1

        return cnt

你可能感兴趣的:(算法)