美文网首页
leetcode--560--和为K的子数组

leetcode--560--和为K的子数组

作者: minningl | 来源:发表于2020-07-20 23:37 被阅读0次

    题目:
    给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。

    示例 1 :

    输入:nums = [1,1,1], k = 2
    输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
    

    说明 :

    数组的长度为 [1, 20,000]。
    数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。
    

    链接:https://leetcode-cn.com/problems/subarray-sum-equals-k

    思路:
    1、遍历整个数组,用一个字典保存数组中和为特定值的数量,如果sum-k在字典中,则返回值次数加上字典对应的value值

    Python代码:

    class Solution(object):
       def subarraySum(self, nums, k):
           """
           :type nums: List[int]
           :type k: int
           :rtype: int
           """
           sum = 0
           cnt = 0
           dt = {}
    
           dt[0] = 1
           for i in range(len(nums)):
               sum += nums[i]
               if sum-k in dt:
                   cnt += dt[sum-k]
               if sum not in dt:
                   dt[sum] = 0
               dt[sum] += 1
           return cnt
    

    相关文章

      网友评论

          本文标题:leetcode--560--和为K的子数组

          本文链接:https://www.haomeiwen.com/subject/csdpkktx.html