题目:在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。
这一题很容易想到O(n*n)的算法,但是显然不是很优。然后考虑了很久,也没有想出来。参考书上的思想。
代码如下:
class Solution {
public:
long InversePairs(vector<int> data){
long length=data.size();
if(length<=0)
return 0;
vector<int> copy(data);//开辟空间复制
long count=InversePairsCore(data,copy,0,length-1);
vector<int>(copy).swap(copy);//释放vector内存
return count%1000000007;
}
long InversePairsCore(vector<int>& data,vector<int>& copy,int low,int high){
if(low==high){
copy[low]=data[low];
return 0;
}
long length=(high-low)/2;
long left=InversePairsCore(copy,data,low,low+length);
long right=InversePairsCore(copy,data,low+length+1,high);
long i=low+length;//i为前半段最后一个数字的下标
long j=high;//j为后半段最后一个数字的下标
long indexcopy=high;
long cnt=0;
while(i>=low && j>=low+length+1){
if(data[i]>data[j]){
copy[indexcopy--]=data[i--];
cnt+=(j-low-length);
}
else{
copy[indexcopy--]=data[j--];
}
}
for(;i>=low;--i)
copy[indexcopy--]=data[i];
for(;j>=low+length+1;--j)
copy[indexcopy--]=data[j];
return left+right+cnt;
}
};
这份代码不是我写的,我写的没有运行通过,调了很久,没找到错误在哪。弄了一下午,乏了,先不调了。
本文介绍了一种高效计算数组中逆序对总数的方法。利用归并排序的思想,通过递归分解数组,并在合并过程中计算逆序对数量,最终实现O(n log n)的时间复杂度。

被折叠的 条评论
为什么被折叠?



