题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数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
class Solution {
public:
int InversePairs(vector<int> data) {
if(data.size() <= 1)
return 0;
int len = data.size();
vector<int>copy(len);
long long res = merge(data,copy,0,len-1);
return res%1000000007;
}
// copy不加引用会影响超时。。。。。。
long long merge(vector<int> &data,vector<int> ©,int l,int r){
if(l == r) return 0;
int m = (l+r)>>1;
long long res1 = merge(data,copy,l,m);
long long res2 = merge(data,copy,m+1,r);
int i = m;
int j = r;
int index = r;
//刚开始这个sum定义为int了。。。
long long sum = 0;
while(i >= l && j >= m+1){
if(data[i] > data[j]){
copy[index--] = data[i--];
sum += j - m;
}
else
copy[index--] = data[j--];
}
while(i >= l)
copy[index--] = data[i--];
while(j >= m+1)
copy[index--] = data[j--];
for(int i = l; i <= r; i++)
data[i] = copy[i];
return (sum+res1+res2) % 1000000007;
}
};