-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy path0327-count-of-range-sum.js
58 lines (51 loc) · 1.53 KB
/
0327-count-of-range-sum.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* 327. Count of Range Sum
* https://leetcode.com/problems/count-of-range-sum/
* Difficulty: Hard
*
* Given an integer array nums and two integers lower and upper, 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
* inclusive, where i <= j.
*/
/**
* @param {number[]} nums
* @param {number} lower
* @param {number} upper
* @return {number}
*/
var countRangeSum = function(nums, lower, upper) {
const result = [0];
for (let i = 0; i < nums.length; i++) {
result.push(result[i] + nums[i]);
}
function mergeSort(input, left, right) {
if (left >= right) return 0;
const middle = Math.floor((left + right) / 2);
let count = mergeSort(input, left, middle) + mergeSort(input, middle + 1, right);
let i = left;
let j = middle + 1;
let k = middle + 1;
while (i <= middle) {
while (j <= right && input[j] - input[i] < lower) j++;
while (k <= right && input[k] - input[i] <= upper) k++;
count += k - j;
i++;
}
const sorted = [];
i = left;
j = middle + 1;
while (i <= middle || j <= right) {
if (i > middle) sorted.push(input[j++]);
else if (j > right) sorted.push(input[i++]);
else if (input[i] <= input[j]) sorted.push(input[i++]);
else sorted.push(input[j++]);
}
for (let i = 0; i < sorted.length; i++) {
input[left + i] = sorted[i];
}
return count;
}
return mergeSort(result, 0, result.length - 1);
};