牛客网竟有如此不为人知的惊天bug!!!
请教下各位数组中的逆序对这个题我到底哪错了。。老告诉我运行时间过大,求大神给个好方法。。
https://www.nowcoder.com/practice/96bd6684e04a44eb80e6a68efc0ec6c5?tpId=13&tqId=11188&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
int InversePairs(vector<int> data) {
if(data.empty())
return 0;
return merge(data,0,data.size()-1);
}
int merge(vector<int>&data,int start,int end){
if(start>=end)
return 0;
int mid=(end-start)/2+start;
int leftcount=merge(data,start,mid);
int rightcount=merge(data,mid+1,end);
int cnt=0;
vector<int>temp(data.size());
int i=start;
int j=mid+1;
int k=start;
while(i!=mid+1&&j!=end+1){
if(data[i]>data[j]){
temp[k++]=data[j++];
cnt+=mid+1-i;
if(cnt>1000000007)
cnt%=1000000007;
}
else
temp[k++]=data[i++];
}
while(i!=mid+1){
temp[k++]=data[i++];
}
while(j!=end+1){
temp[k++]=data[j++];
}
for(int i=start;i<=end;i++){
data[i]=temp[i];
}
return (leftcount+rightcount+cnt)%1000000007;
}