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
|
class Solution {
private static int[] help = new int[500001];
public int reversePairs(int[] nums) {
return count(nums, 0, nums.length - 1);
}
public int count(int[] nums, int left, int right) {
if (left == right) {
return 0;
}
int middle = left + (right - left) / 2;
int leftPairs = count(nums, left, middle);// 左范围答案
int rightPairs = count(nums, middle + 1, right);// 右范围答案
int crossPairs = merge(nums, left, middle, right);// 跨越左右产生的答案
return leftPairs + rightPairs + crossPairs;
}
private int merge(int[] nums, int left, int middle, int right) {
// count 此时左右两边已经有序,对于计算符合要求的值来说更加方便了
int ii = left;
int jj = middle + 1;
int res = 0;
int sum = 0;
for (int i = ii; i <= middle; i++) {
while (jj <= right && (long) nums[i] > (long)2 * nums[jj]) {
sum += 1;
jj++;
}
res += sum;
}
// sort
int i = left;
int j = middle + 1;
int index = left;
while (i <= middle && j <= right) {
if (nums[i] < nums[j]) {
help[index++] = nums[i];
i++;
} else {
help[index++] = nums[j];
j++;
}
}
while (i <= middle) {
help[index++] = nums[i++];
}
while (j <= right) {
help[index++] = nums[j++];
}
for (int k = left; k <= right; k++) {
nums[k] = help[k];
}
return res;
}
}
|