剑指offer——数组中的逆序数对
发布时间:2023-02-02 23:11:40 203 相关标签: # 数据
题目描述:
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数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
思路1:遍历数组,检查是否是逆序数对,记录个数。时间复杂度过高
class Solution {
public:
int InversePairs(vector data) {
if(data.size()<2)
return 0;
int p=0;
for(int i=0;i<data.size();i++){
for(int j=i+1;j<data.size();j++){
if(data[i]>data[j])
p++;
}
}
return p%1000000007;
}
};
剑指offer给出的参考答案
class Solution {
public:
int InversePairs(vector data) {
if(data.size()<2)
return 0;
int length=data.size();
vector copy(length);
for(int i=0;i<length;i++){
copy[i]=data[i];
}
long long count=InverseCore(data,copy,0,length-1);
return count%1000000007;
}
//data是子数组有序,copy是合并后有序数组
long long InverseCore(vector& data,vector& copy,int start,int end){
if(start==end){
copy[start]=data[start];
return 0;
}
int length=(end-start)>>1;
long long left=InverseCore(copy,data,start,start+length);
long long right=InverseCore(copy,data,start+length+1,end);
int i=start+length;
int j=end;
int copyindex=end;
long long count=0;
while(i>=start&&j>=start+length+1){
if(data[i]>data[j]){
copy[copyindex--]=data[i--];
count+=j-start-length;
}else{
copy[copyindex--]=data[j--];
}
}
while(i>=start){
copy[copyindex--]=data[i--];
}
while(j>=start+length+1){
copy[copyindex--]=data[j--];
}
return left+right+count;
}
};
文章来源: https://blog.51cto.com/u_15855860/5812326
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报