题目:
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
知识点:
归并排序算法
思路:
参考:
答案:
public class Solution {
public int InversePairs(int [] array) {
if(array.length==0){return 0;}
int[] copy = new int[array.length];//排序后,从小到大排列的数组
for(int i=0;i<array.length;i++){
copy[i]=array[i];
}
int count=InversePairs(array,copy,0,array.length-1);
return count;
}
public int InversePairs(int [] array,int [] copy,int low,int high){
if(low==high){return 0;}
int mid = (low+high)/2;
int leftCount = InversePairs(array,copy,low,mid)%1000000007;
int rightCount = InversePairs(array,copy,mid+1,high)%1000000007;
int count=0;//逆序对的数量
int i=mid;//前半部分数组
int j=high;//后半部分数组
int locCopy=high;//copy数组中的下标
while(i>=low && j>mid){//循环比较大小,计数,知道有一组比较完
if(array[i]>array[j]){
count += j-mid;//记录逆序数
copy[locCopy--] = array[i--];//比较后,将大的数放后面
if(count>=1000000007)//数值过大求余
{
count%=1000000007;
}
}else{
copy[locCopy--] = array[j--];
}
}
for(;i>=low;i--){//将比较后,剩余的数组依次放在copy数组中
copy[locCopy--] = array[i];
}
for(;j>mid;j--){//将比较后,剩余的数组依次放在copy数组中
copy[locCopy--] = array[j];
}
for(int s=low;s<=high;s++){//更改排序后的原数组中顺序
array[s]=copy[s];
}
return (leftCount+rightCount+count)%1000000007;//count是最后一次记录的逆序数值
}
}