Given an integer arraynums, return the number of range sums that lie in[lower, upper]inclusive.
Range sumS(i, j)is defined as the sum of the elements innumsbetween indicesiandj(i≤j), inclusive.
Note:
A naive algorithm of O(n^2) is trivial. You MUST do better than that.
Example:
Givennums=[-2, 5, -1],lower=-2,upper=2,
Return3.
The three ranges are :[0, 0],[2, 2],[0, 2]and their respective sums are:-2, -1, 2.
public class Solution {
public int countRangeSum(int[] nums, int lower, int upper) {
TreeMap<Long, Long> map = new TreeMap();
map.put((long)0, (long)1);
long sum = 0;
int count = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
long fromKey = sum - upper;
long toKey = sum - lower;
Map<Long, Long> subMap = map.subMap(fromKey, true, toKey, true);
for (long value : subMap.values()) {
count += value;
}
if (map.containsKey(sum)) {
map.put(sum, map.get(sum) + 1);
}
else {
map.put(sum, (long)1);
}
}
return count;
}
}