327 Count of Range Sum
327. Count of Range Sum
1. Question
2. Implementation
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;
}
}3. Time & Space Complexity
Last updated