Skip to content

Commit c1200d0

Browse files
committed
Runtime: 150 ms (Top 60.29%) | Memory: 85.20 MB (Top 11.76%)
1 parent fd4a0bf commit c1200d0

File tree

1 file changed

+45
-49
lines changed

1 file changed

+45
-49
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,59 +1,55 @@
1+
// Runtime: 150 ms (Top 60.29%) | Memory: 85.20 MB (Top 11.76%)
2+
13
/**
24
* @param {number[]} nums
35
* @return {number}
46
*/
57
var reversePairs = function(nums) {
8+
let numReversePairs = 0;
9+
helper(nums);
10+
return numReversePairs;
611

7-
let ans = mergeSort(nums,0,nums.length-1);
8-
return ans;
12+
function helper(nums) {
13+
if (nums.length <= 1) return nums;
14+
const length = nums.length;
15+
const left = helper(nums.slice(0, Math.floor(length/2)));
16+
const right = helper(nums.slice(Math.floor(length/2)));
17+
return merge(left, right);
18+
}
919

10-
11-
};
12-
13-
var mergeSort = function(nums,l,h){
14-
if(l>=h){
15-
return 0;
16-
}
17-
let m = Math.floor((l+h)/2);
18-
let inv = mergeSort(nums,l,m);
19-
inv = inv + mergeSort(nums,m+1,h);
20-
inv = inv + merge(nums,l,m,h);
21-
return inv;
22-
}
23-
24-
var merge = function (nums,l,m,h){
25-
let cnt = 0;
26-
let j=m+1;
27-
for(let i=l;i<=m;i++){
28-
while(j<=h && nums[i]> 2*nums[j]){
29-
j++;
30-
}
31-
cnt = cnt+(j-(m+1));
20+
function merge(left, right) {
21+
const nums_sorted = [];
22+
let leftIndex = 0;
23+
let rightIndex = 0;
24+
while(leftIndex < left.length && rightIndex < right.length) {
25+
if (left[leftIndex] > 2 * right[rightIndex]) {
26+
numReversePairs += (left.length - leftIndex);
27+
rightIndex++;
28+
} else {
29+
leftIndex++;
30+
}
31+
}
32+
leftIndex = 0;
33+
rightIndex = 0;
34+
while (leftIndex < left.length && rightIndex < right.length) {
35+
if (left[leftIndex] < right[rightIndex]) {
36+
nums_sorted.push(left[leftIndex]);
37+
leftIndex++;
38+
} else {
39+
let cur = leftIndex;
40+
nums_sorted.push(right[rightIndex]);
41+
rightIndex++;
42+
}
3243
}
33-
34-
let left = l, right=m+1,temp=[];
35-
while(left<=m && right<=h){
36-
if(nums[left]<=nums[right]){
37-
temp.push(nums[left]);
38-
left++;
39-
}
40-
else{
41-
temp.push(nums[right]);
42-
right++;
43-
}
44+
while (leftIndex < left.length) {
45+
nums_sorted.push(left[leftIndex]);
46+
leftIndex++;
4447
}
45-
while(left<=m){
46-
temp.push(nums[left]);
47-
left++;
48+
while (rightIndex < right.length) {
49+
nums_sorted.push(right[rightIndex]);
50+
rightIndex++;
4851
}
49-
while(right<=h){
50-
temp.push(nums[right]);
51-
right++;
52-
}
53-
for(let i=l;i<=h;i++){
54-
nums[i]=temp[i-l];
55-
}
56-
return cnt;
57-
58-
}
59-
52+
return nums_sorted;
53+
}
54+
55+
};

0 commit comments

Comments
 (0)