【剑指Offer】数组中的逆序对

题目

在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对,输入一个数组,求出这个数组中的逆序对的总数。

实现

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
public int InversePairs(int[] array) {
if (array == null || array.length < 1)
return 0;

int[] aux = new int[array.length];

for (int i = 0; i < array.length; i++)
aux[i] = array[i];

return sortAndCount(array, aux, 0, array.length - 1);
}

private int sortAndCount(int[] array, int[] aux, int start, int end){
if (start == end)
return 0;

int mid = (start + end) / 2;

int leftCount = sortAndCount(array, aux, start, mid);
int rightCount = sortAndCount(array, aux, mid + 1, end);
int splitCount = countSplitInv(array, aux, start, mid, end);

return (leftCount + rightCount + splitCount) % 1000000007;
}

private int countSplitInv(int[] array, int[] aux, int start, int mid, int end) {
int count = 0;
int j = start;
int k = mid + 1;

for (int i = start; i <= end; i++) {
if (j > mid)
array[i] = aux[k++];
else if (k > end)
array[i] = aux[j++];
else if (aux[j] < aux[k])
array[i] = aux[j++];
else {
count += mid - j + 1;
array[i] = aux[k++];

if (count > 1000000007)
count %= 1000000007;
}
}

for (int i = start; i <= end; i++)
aux[i] = array[i];

return count;
}