-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathReverse Pairs.js
55 lines (51 loc) · 1.41 KB
/
Reverse Pairs.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
// Runtime: 150 ms (Top 60.29%) | Memory: 85.20 MB (Top 11.76%)
/**
* @param {number[]} nums
* @return {number}
*/
var reversePairs = function(nums) {
let numReversePairs = 0;
helper(nums);
return numReversePairs;
function helper(nums) {
if (nums.length <= 1) return nums;
const length = nums.length;
const left = helper(nums.slice(0, Math.floor(length/2)));
const right = helper(nums.slice(Math.floor(length/2)));
return merge(left, right);
}
function merge(left, right) {
const nums_sorted = [];
let leftIndex = 0;
let rightIndex = 0;
while(leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] > 2 * right[rightIndex]) {
numReversePairs += (left.length - leftIndex);
rightIndex++;
} else {
leftIndex++;
}
}
leftIndex = 0;
rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
nums_sorted.push(left[leftIndex]);
leftIndex++;
} else {
let cur = leftIndex;
nums_sorted.push(right[rightIndex]);
rightIndex++;
}
}
while (leftIndex < left.length) {
nums_sorted.push(left[leftIndex]);
leftIndex++;
}
while (rightIndex < right.length) {
nums_sorted.push(right[rightIndex]);
rightIndex++;
}
return nums_sorted;
}
};