【leetcode】327. Count of Range Sum
阿新 • • 發佈:2018-04-14
htm color keys clas .html enum equals code range
題目如下:解題思路:本題是 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