题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
输入描述:
题目保证输入的数组中没有的相同的数字
数据范围:
对于%50的数据,size<=10^4
对于%75的数据,size<=10^5
对于%100的数据,size<=2*10^5
输入:1,2,3,4,5,6,7,0
输出:7
C++代码
class Solution {
public:
int InversePairs(vector<int> data) {
int n=data.size();
if(n<=1)
return 0;
vector<int> copy(data.begin(),data.end());
long result=merge(copy,data,0,n-1)%1000000007;
return result;
}
long merge(vector<int> ©,vector<int> &data,int start,int end)
{
if(start>=end)
return 0;
int mid=(start+end)/2;
int start1=start,end1=mid;
int start2=mid+1,end2=end;
long left=merge(copy,data,start1,end1);
long right=merge(copy,data,start2,end2);
int i=end1,j=end2;
long count=0;
while(i>=start1&&j>=start2)
{
if(data[i]>data[j])
{
copy[end--]=data[i--];
count=count+(j-start2+1);
}else
copy[end--]=data[j--];
}
while(i>=start1)
copy[end--]=data[i--];
while(j>=start2)
copy[end--]=data[j--];
for(int i=start1;i<=end2;i++)
data[i]=copy[i];
return left+right+count;
}
};