码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 560. Subarray Sum Equals K_Medium

时间:2018-06-21 11:28:06      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:一个   hose   利用   problem   tps   返回   NPU   tin   class   

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

Example 1:

Input:nums = [1,1,1], k = 2
Output: 2

 

Note:

  1. The length of the array is in range [1, 20,000].
  2. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

 

这个题目思路是利用cumulative sum, 前面数字之和去计算. 参考Leetcode 原题Solution.

建一个diction, 记录 sum 出现过的次数, 然后每次用sum - target, 如果存在在dction里面, count += d[sum-target], 最后返回count. 如果直到这个思路之后其实不难, 否则还蛮难想的.

 

class Solution:
    def subarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
    
    d, count,s = {0:1}, 0,0  # 最开始有0:1 是因为"" 的sum是0, 所以初始为1
    for num in nums:
        s += num
        if s - k in d:
            count += d[s-k]
        if s not in d:
            d[s] = 1
        else:
            d[s] += 1

    return count    

 

[LeetCode] 560. Subarray Sum Equals K_Medium

标签:一个   hose   利用   problem   tps   返回   NPU   tin   class   

原文地址:https://www.cnblogs.com/Johnsonxiong/p/9206892.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!