题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
输入描述:
题目保证输入的数组中没有的相同的数字
数据范围:
对于%50的数据,size<=10^4
对于%75的数据,size<=10^5
对于%100的数据,size<=2*10^5
示例1
输入
1,2,3,4,5,6,7,0
输出
7
题解一
采用插入排序,元素交换位置的次数即为逆序对数。复杂度为O(n^2),通过率只有50%。
public class Solution {
public int InversePairs(int [] a) {
long count = 0;
for(int i=1;i<a.length;i++) {
for(int j=i;j>0 && a[j] < a[j-1];j--) {
count++;
a[j] = a[j] + a[j-1];
a[j-1] = a[j] - a[j-1];
a[j] = a[j] - a[j-1];
}
}
return (int)(count % 1000000007);
}
}
题解二
采用归并排序的思想
public class Solution {
public int[] aux;
public int InversePairs(int [] a) {
aux = new int[a.length];
long count = mergeSort(a, 0, a.length-1);
return (int)(count % 1000000007);
}
public long mergeSort(int[] a, int low, int high) {
if(low >= high)
return 0;
int mid = (low + high)/2;
long leftCount = mergeSort(a, low, mid);
long rightCount = mergeSort(a, mid + 1, high);
long midCount = merge(a, low, mid, high);
return leftCount + midCount + rightCount;
}
public long merge(int[] a, int low, int mid, int high) {
for(int i=low;i<=high;i++) {
aux[i] = a[i];
}
int i = low;
int j = mid + 1;
long count = 0;
for(int k=low;k<=high;k++) {
if(i > mid) {
a[k] = aux[j++];
} else if(j > high) {
a[k] = aux[i++];
}else if(aux[i] <= aux[j]) {
a[k] = aux[i++];
} else {
a[k] = aux[j++];
count += mid - i + 1;
}
}
return count;
}
}