题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
解题思路
这道题是归并排序的变形。我在思考的时候也想到可以用分治的思想来解决,但是在两个子数组如何合并的问题上没有想清楚。
这道题的解题代码,其实可以在归并排序的基础上进行。其与归并排序的区别在于,子数组合并的时候应该统计左子数组中数字比右子数组中数字大的逆序对。在合并的时候,有子数组都已排好序的前提,可以帮助我们进行逆序对的统计,具体过程看下面的示例。
代码
public class InversePairs {
public int InversePairs(int [] array) {
if(array==null || array.length==0){
return 0;
}
int[] copy = new int[array.length];
for(int i=0;i<array.length;i++){
copy[i] = array[i];
}
return InversePairsCore(array, copy, 0, array.length-1);
}
public int InversePairsCore(int[] array, int[] copy, int start, int end){
if(start==end){
copy[start] = array[start];
return 0;
}
int length = (end-start)/2;
int left = InversePairsCore(array, copy, start, start+length)%1000000007;
int right = InversePairsCore(array, copy, start+length+1, end)%1000000007;
int i = start+length;
int j = end;
int indexCopy = end;
int count = 0;
while(i>=start && j>=start + length + 1){
if(array[i]>array[j]){
copy[indexCopy--] = array[i--];
count+=j-start-length;
if(count>=1000000007)//数值过大求余
{
count%=1000000007;
}
}else{
copy[indexCopy--] = array[j--];
}
}
for(;i>=start;i--){
copy[indexCopy--] = array[i];
}
for(;j>=start+length+1;j--){
copy[indexCopy--] = array[j];
}
for(int s=start;s<=end;s++)
{
array[s] = copy[s];
}
return (left + right + count)%1000000007;
}
}