LintCode 1293: Count of Range Sum

1293. Count of Range Sum

Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.
Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j (i ≤ j), inclusive.

Example

Example 1:

Input:[-2, 5, -1],-2,2
Output:3
Explanation:The three ranges are : [0, 0], [2, 2], [0, 2] and their respective sums are: -2, -1, 2.

Example 2:

Input:[0,-3,-3,1,1,2],3,5
Output:2
Explanation:The three ranges are : [3, 5], [4, 5] and their respective sums are: 4, 3.

Notice

A naive algorithm of O(n^2) is trivial. You MUST do better than that.

Input test data (one parameter per line)How to understand a testcase?

解法1:

参考的网上的思路。

首先得到presums,可用数组也可不用。

对于每个presums[i],我们要得到所有的nums[j]使得lower<=presums[i] - presums[j]<=upper,即

presums[i] >= presumes[j] + lower //我们要找到所有presums[i] - lower >= presums[j]的presums[j],当j小于一定值后所有的presums[j'都满足,所以取upper。
presums[i] <= presums[j] + upper //我们要找到所有presums[i] - upper <= presums[j]的presums[j],当j大于一定值后所有的presums[j]都满足,所以取lower。

 

class Solution {
public:
    /**
     * @param nums: a list of integers
     * @param lower: a integer
     * @param upper: a integer
     * @return: return a integer
     */
    int countRangeSum(vector<int> &nums, int lower, int upper) {
        int n = nums.size();
        multiset<long long> ms;
        long long presums = 0;
        int result = 0;
        ms.insert(0);

        for (int i = 0; i < n; ++i) {
            presums += nums[i];
            result += distance(ms.lower_bound(presums - upper), ms.upper_bound(presums - lower));
            ms.insert(presums);
        }
        
        return result;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值