20170603-leetcode-560-Subarray Sum Equals K

1.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.

Example 1:

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

Note:

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

解读
给定一个整数数组,和一个整数k,求有多少个连续子序列的和为k。

2.Solution

解题思路:
最能想到的办法就是遍历了,存储前n项的和,然后递减回去,但是超时了

class Solution(object):
    def subarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if nums == []: return 0

        sumlist, N = [nums[0]], 0
        for i in range(1, len(nums)):
            sumlist.append(sumlist[-1] + nums[i])
        for i in range(len(sumlist)):
            if sumlist[i] == k:
                N = N + 1
            for j in range(i):
                if sumlist[i] - sumlist[j] == k:
                    N = N + 1
        #print(N)
        return N

那么可以想到:通过记录前n项和的次数,来快速得到解,什么意思呢,
比如我们已经把前面n-1项和的次数放入到了词典中,比如{ S1 :2, S2 :3, S3 :3 … Si :V… Sn1:k },这时候新来一个 Sn , 如果 Sn -K(题目中给的值:要求的和)= Si ,恰好在上面次数词典中,我们就可以直接把次数V提取出来。

class Solution(object):
    def subarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        count,cur,res={0:1},0,0
        for num in nums:
            cur=cur+num#计算前n项和
            # (如果前n项和)cur-(需要求的和)k in (前n项和次数)词典中,那么get出来次数
            res=res+count.get(cur-k,0)
            count[cur]=count.get(cur,0)+1 #(如果前n项和)cur(的次数)在字典中加1
        return res
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值