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