-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path493. Reverse Pairs
62 lines (51 loc) · 1.53 KB
/
493. Reverse Pairs
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
59
60
61
62
Runtime 132 ms
Beats 27.56%
Memory 51.3 MB
Beats 82.74%
class Solution {
private int count;
public int reversePairs(int[] nums) {
count = 0;
mergeSort(nums, 0, nums.length - 1);
return count;
}
private int[] mergeSort(int[] nums, int left, int right) {
if (left == right) {
return new int[]{nums[left]};
}
int mid = left + (right - left) / 2;
int[] leftSorted = mergeSort(nums, left, mid);
int[] rightSorted = mergeSort(nums, mid + 1, right);
int i = 0, j = 0;
int lenL = leftSorted.length;
int lenR = rightSorted.length;
while (i < lenL) {
while (j < lenR && leftSorted[i] > 2 * (long)rightSorted[j]) {
j++;
}
count += j;
i++;
}
return merge(leftSorted, rightSorted);
}
private int[] merge(int[] leftSorted, int[] rightSorted) {
int lenL = leftSorted.length;
int lenR = rightSorted.length;
int i = 0, j = 0, index = 0;
int[] sorted = new int[lenL + lenR];
while (i < lenL && j < lenR) {
if (leftSorted[i] <= rightSorted[j]) {
sorted[index++] = leftSorted[i++];
} else {
sorted[index++] = rightSorted[j++];
}
}
while (i < lenL) {
sorted[index++] = leftSorted[i++];
}
while (j < lenR) {
sorted[index++] = rightSorted[j++];
}
return sorted;
}
}