LeetCode 560 Subarray Sum Equals K (Python)

Posted by 小明MaxMing on April 26, 2020

题目

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

解题思路

代码

from collections import defaultdict
class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
        dic = defaultdict(int)
        s = 0
        dic[0] = 1
        res = 0
        for n in nums:
            s += n
            if s - k in dic:
                res += dic[s - k]
            dic[s] += 1
        return res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅