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
|
public class Solution2 {
private int res = 0;
public int InversePairs(int[] array) {
int[] copy = new int[array.length];
merge_sort(array, copy, 0, array.length - 1);
return res;
}
private void merge(int[] array, int[] copy, int left, int mid, int right) {
int i = left, j = mid + 1;
for (int index_copy = left; index_copy <= right; index_copy++) {
if (i > mid) {
copy[index_copy] = array[j++];
} else if (j > right) {
copy[index_copy] = array[i++];
} else if (array[i] > array[j]) {
res += mid - i + 1;
res %= 1000000007;
copy[index_copy] = array[j++];
} else {
copy[index_copy] = array[i++];
}
}
for(int m=left;m<=right;m++) //复制别忘了
array[m]=copy[m];
}
private void merge_sort(int[] array, int[] copy, int start, int end) {
if (start < end) {
int mid = start + (end - start) / 2;
merge_sort(array, copy, start, mid);
merge_sort(array, copy, mid + 1, end);
merge(array, copy, start, mid, end);
}
}
public static void main(String[] args) {
Solution2 s = new Solution2();
int[] array = {1, 8, 3, 4, 5, 6, 7, 0};
System.out.println(s.InversePairs(array));
}
}
|