-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
43 lines (41 loc) · 1.14 KB
/
Solution.java
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
class Solution {
private static int[] tmp = new int[50010];
public int reversePairs(int[] nums) {
return mergeSort(nums, 0, nums.length - 1);
}
private int mergeSort(int[] nums, int left, int right) {
if (left >= right) {
return 0;
}
int mid = (left + right) >> 1;
int res = mergeSort(nums, left, mid) + mergeSort(nums, mid + 1, right);
int i = left, j = mid + 1, k = 0;
while (i <= mid && j <= right) {
if ((long) nums[i] <= (long) 2 * nums[j]) {
++i;
} else {
res += (mid - i + 1);
++j;
}
}
i = left;
j = mid + 1;
while (i <= mid && j <= right) {
if (nums[i] <= nums[j]) {
tmp[k++] = nums[i++];
} else {
tmp[k++] = nums[j++];
}
}
while (i <= mid) {
tmp[k++] = nums[i++];
}
while (j <= right) {
tmp[k++] = nums[j++];
}
for (i = left; i <= right; ++i) {
nums[i] = tmp[i - left];
}
return res;
}
}