标签:rate info strong int 思路 subarray 遍历 计数 res
题目如下:解题思路:本题是 560. Subarray Sum Equals K 的升级版,可以参见560的解题思路。唯一的区别是560只给了一个精确的和K,而本题是给了一个和的范围,所以最终计数的时候遍历一下题目要求的区间即可。
代码如下:
class Solution(object): def countRangeSum(self, nums, lower, upper): """ :type nums: List[int] :type lower: int :type upper: int :rtype: int """ if len(nums) == 0: return 0 dp = [0 for x in nums] dp[-1] = nums[-1] keys = [] dic = {} dic[dp[-1]] = 1 keys.append(dp[-1]) for i in xrange(-2, -len(nums) - 1, -1): dp[i] = dp[i + 1] + nums[i] if dic.has_key(dp[i]): dic[dp[i]] += 1 else: dic[dp[i]] = 1 keys.append(dp[i]) res = 0 keys.sort() print dic,dp for i, v in enumerate(dp): if v >= lower and v <= upper: res += 1 dic[v] -= 1 import bisect left = bisect.bisect_left(keys,v - upper) right = bisect.bisect_right(keys,v - lower) #print left,right,keys while left < right and left < len(keys): if dic.has_key(keys[left]): res += dic[keys[left]] left += 1 return res
【leetcode】327. Count of Range Sum
标签:rate info strong int 思路 subarray 遍历 计数 res
原文地址:https://www.cnblogs.com/seyjs/p/8831028.html