• 【leetcode】327. 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
  • 相关阅读:
    SharePoint 2013 配置我的网站 图文引导
    关于SharePoint REST中的授权的研究
    SharePoint重置密码功能Demo
    SharePoint 沙盒解决方案 VS 场解决方案
    移动设备和SharePoint 2013
    win32
    win32
    链表复习-1
    win32
    洛谷基础算法
  • 原文地址:https://www.cnblogs.com/seyjs/p/8831028.html
Copyright © 2020-2023  润新知