1
/**
2
* @param {number[]} nums
3
* @return {number}
4
*/
5
var reversePairs = function (nums) {
6
let numReversePairs = 0;
7
helper(nums);
8
return numReversePairs;
9

10
function helper(nums) {
11
if (nums.length <= 1) return nums;
12
const length = nums.length;
13
const left = helper(nums.slice(0, Math.floor(length / 2)));
14
const right = helper(nums.slice(Math.floor(length / 2)));
15
return merge(left, right);
16
}
17

18
function merge(left, right) {
19
const nums_sorted = [];
20
let leftIndex = 0;
21
let rightIndex = 0;
22
while (leftIndex < left.length && rightIndex < right.length) {
23
if (left[leftIndex] > 2 * right[rightIndex]) {
24
numReversePairs += left.length - leftIndex;
25
rightIndex++;
26
} else {
27
leftIndex++;
28
}
29
}
30
leftIndex = 0;
31
rightIndex = 0;
32
while (leftIndex < left.length && rightIndex < right.length) {
33
if (left[leftIndex] < right[rightIndex]) {
34
nums_sorted.push(left[leftIndex]);
35
leftIndex++;
36
} else {
37
let cur = leftIndex;
38
nums_sorted.push(right[rightIndex]);
39
rightIndex++;
40
}
41
}
42
while (leftIndex < left.length) {
43
nums_sorted.push(left[leftIndex]);
44
leftIndex++;
45
}
46
while (rightIndex < right.length) {
47
nums_sorted.push(right[rightIndex]);
48
rightIndex++;
49
}
50
return nums_sorted;
51
}
52
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0