逆序对

归并算法求逆序,基于分治的,剑指offer上那个感觉有问题啊。每次合并之后没有把辅助数组里的值放回原来的地方,我还以为是边界没写好看了半天。

而且这个和昨天的360那个跳水计算的是一样的,只不过逆序对的记录是记录每个点上的,在每个点上有多少需要把前面的加起来。

class Solution {
public:
    int f(vector<int> &data,vector<int> &copy,int i ,int j) {
        if(i == j) {
            copy[i] = copy[i];
            return 0;
        } else {
            int mid = ( j - i )/2;
            int left = f(data,copy,i,mid+i);
            int right = f(data,copy,mid+1+i,j);
            int m = i+mid, n = j, indexcopy = j;
            int count = 0;
            while(m>=i&&n>=i+mid+1) {
                if(data[m]>data[n]) {
                    count = (count + n-i-mid)%1000000007;
                    copy[indexcopy--] = data[m--];
                } else {
                    copy[indexcopy--] = data[n--];
                }
            }
            for(;n>=i+mid+1;n--) copy[indexcopy--] = data[n];
            for(;m>=i;m--)  copy[indexcopy--] = data[m];
	    for(int h = i; h <= j;h++) data[h] = copy[h];   //就是没有这一句
            return (left+count+right)%1000000007;
        }
    }
    int InversePairs(vector<int> data) {
        if(data.size()==0) return 0;
        vector<int> copy(data.size(),0);
        for(int i = 0; i < data.size(); i++) copy[i] = data[i];
        return f(data,copy,0,data.size()-1);
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值