剑指offer 35.数组中的逆序对

剑指offer 35.数组中的逆序对

题目

题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007

输入描述:
题目保证输入的数组中没有的相同的数字

数据范围:

对于%50的数据,size<=10^4
对于%75的数据,size<=10^5
对于%100的数据,size<=2*10^5

思路

这题好麻烦的,最后选择了模拟归并排序的方法,分成最小的块然后进行归并,归并时内部的逆序对就已经计算了,不需要再计算一次。
以158,236为例子,首先1<2,逆序不用计算,然后5>3,应该放3,逆序增加5,8两个数字,为mid-l+1,行了。

代码

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
long count = 0;

public void merge(int[] array, int[] copy, int start, int end) {
if (start >= end) {
return;
}

int mid = (end - start) / 2 + start;
merge(array, copy, start, mid);
merge(array, copy, mid + 1, end);
int l = start;
int r = mid + 1;
int temp = start;
while (l <= mid && r <= end) {
if (array[l] <= array[r]) {
copy[temp++] = array[l++];
} else {
count += mid - l + 1;
copy[temp++] = array[r++];
if (count > 1000000007) {
count %= 1000000007;
}
}
}
while (l <= mid) {
copy[temp++] = array[l++];
}
while (r <= end) {
copy[temp++] = array[r++];
}
for (int i = start; i <= end; i++) {
array[i] = copy[i];
}
}

public int InversePairs(int[] array) {
int start = 0;
int end = array.length - 1;
int[] copy = new int[array.length];
merge(array, copy, start, end);
return (int) count;
}
---本文结束,感谢阅读---