leetcode327. Count of Range Sum
Posted seyjs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode327. Count of Range Sum相关的知识,希望对你有一定的参考价值。
题目如下:解题思路:本题是 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
以上是关于leetcode327. Count of Range Sum的主要内容,如果未能解决你的问题,请参考以下文章
leetcode327. Count of Range Sum
Leetcode327: Count of Range Sum 范围和个数问题
LeetCode Count of Smaller Numbers After Self