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;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章