1. Description
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.
Note:
A naive algorithm of O(n2) is trivial. You MUST do better than that.
Example:
Given nums = [-2, 5, -1], lower = -2, upper = 2,
Return 3.
The three ranges are : [0, 0], [2, 2], [0, 2] and their respective sums are: -2, -1,
2.
2. Analysis
题目的意思是找出这样符合条件的子区间的数目,这样的子区间需要满足区间内的元素之和在给定区间[lower, upper]之内。简单粗暴的方法当然是穷举完所有的可能子区间再判断计算。
3. code
naive solution , time complexity is O(n2) :
class Solution {
public:
int countRangeSum(vector<int>& nums, int lower, int upper) {
long int sum = 0, tmp = 0;
for(int i = 0; i < nums.size(); i++) {
if(lower <= nums[i] && nums[i] <= upper) {
sum++;
}
tmp = nums[i];
for(int j = i+1; j < nums.size(); j++) {
tmp += nums[j];
if(lower <= tmp && tmp <= upper) {
sum++;
}
}
}
return sum;
}
};
better solution, time complexity is