数组中的逆序对
描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
解题
Solution
/**
* 数组中的逆序对
* 合并排序
*/
public class Solution {
private int count=0;
public int InversePairs(int [] array){
MergeSort(array,0,array.length-1);
return count;
}
private void MergeSort(int[] array, int start, int end) {
if (start>=end)return;
int midle=(start+end)/2;
MergeSort(array,start,midle);//递归
MergeSort(array,midle+1,end);
helper(array,start,midle,end);//合并
}
private void helper(int[] array, int start, int midle, int end) {
int[] temp = new int[end-start+1];//创建临时数组
int k=0,i=start,j=midle+1;
while (i<=midle&&j<=end){
if (array[i]<=array[j]){
temp[k++]=array[i++];//非逆序则正常排序
}else {
temp[k++]=array[j++];
count=(count+midle-i+1)%1000000007;//逆序则加入
}
}
while (i<=midle) temp[k++]=array[i++];
while (j<=end ) temp[k++]=array[j++];
for (int l = 0; l < temp.length; l++) {
array[start+l]=temp[l];
}
}
}