题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数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
public class Solution {
public int ans=0;
public int mod=(int)1e9+7;
public int InversePairs(int [] array) {
merge(array,0,array.length);
return ans;
}
public int cal(int x){
return x<mod?x:x-mod;
}
public void merge(int[] a,int L,int R){//[L,R)
if(L==R-1) return ;
int temp[]=new int[R-L+5];
int mid=(L+R)/2;
int l=L,r=mid;
int cnt=0;
merge(a,L,mid);
merge(a,mid,R);
while(l<mid&&r<R){
if(a[l]>a[r]){
temp[cnt++]=a[r++];
ans=cal(ans+mid-l);
}
else{
temp[cnt++]=a[l++];
}
}
while(l<mid){
temp[cnt++]=a[l++];
}
while(r<R){
temp[cnt++]=a[r++];
}
for(int i=0;i<cnt;i++){
a[L+i]=temp[i];
}
}
}