在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007。
思路分析:
采用归并排序的思想:如给定数组{7,5,6,4},以此来分析逆序对的过程。
(1)长度为4数组分解为两个长度为2的子数组;(7,5) (6,4)
(2)长度为2数组分解为两个长度为1的子数组;(7)和(5) (6)和(4)
(3)把长度为1的子数组合并、排序,并统计逆序对数;
(4)把长度为2的子数组合并、逆序,并统计逆序对数。
public class Solution {
public int InversePairs(int [] array) {
int len=array.length;
if(len<=0)
return 0;
int[] copy=new int[len];
for(int i=0;i<len;i++){
copy[i]=array[i];
}
int count=InversePairsCore(array,copy,0,len-1);
return count;
}
public int InversePairsCore(int[]data,int[] copy,int start,int end){
if(start==end){
return 0;
}
int mid=(start+end)/2;
int left=InversePairsCore(data,copy,start,mid)%1000000007;
int right=InversePairsCore(data,copy,mid+1,end)%1000000007;
int i=mid;
int j=end;
int indexcopy=end;
int count=0;
while(i>=start&&j>=mid+1){
if(data[i]>data[j])
{
count=count+j-mid;
copy[indexcopy--]=data[i--];
if(count>=1000000007)//数值过大求余
count%=1000000007;
}
else
{
copy[indexcopy--]=data[j--];
}
}
for(;i>=start;i--){
copy[indexcopy--]=data[i];
}
for(;j>=mid+1;j--){
copy[indexcopy--]=data[j];
}
for (int k = start; k <= end; k++)
data[k] = copy[k];
return (left+right+count)%1000000007;
}
}