剑指offer-数组中的逆序对

题目描述

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007

思路:

遇到该问题的时候,最直观的方法是用两个for循环进行求解,复杂度为 O(n2) 。理所当然的超时了。
然后思考其他解决方法,看能不能利用已经遍历比较过的信息,进行求解。先考虑从前往后遍历,然后发现很难利用已经计算出来的结果
因此考虑从后往前的遍历,考虑当前判断数字 array[index1] 的逆序对数目,那么我们需要找到该数在 index1 indexend 的位置,从而得到在该位置之前的数字个数。那么理所当然的,我们希望在 index1 之后的数组是有序的。但是这样仍然不能够显著降低复杂度,复杂度仍然是 O(n2) , 原因是什么呢?
原因在于 index1 之前的一部分数组仍然是无序的,因此每次我们都要从后面已经有序的数组从头遍历。因此如果从 index0,index1 该段的数组是有序的呢? 那么我们就可以不必要每次都要从后面的数组从头遍历了。

到这里我们遇到了新的问题,就是怎么保证部分数组有序?而且在保证有序的过程中,怎么计算其中的逆序对数?
在这里我们想到了这个问题和归并排序很像,因此我们考虑用归并排序来解决。

code:

class Solution {
public:
    int InversePairs(vector<int> data) {
        long long sum;
        int length = data.size();
        if(length<=0)
            return 0;
        vector<int> aux;
        for(int i=0;i<length;i++)
            aux.push_back(data[i]);
        sum = guibing(data,aux,0,length-1);
        return sum%1000000007;
    }
    long long guibing(vector<int> &data, vector<int> &aux,int start, int end){
        if(start==end){
            aux[start] = data[start];
            return 0;
        }
        int length = (end-start)/2;
        long long left = guibing(data,aux,start,start+length);
        long long  right = guibing(data,aux,start+length+1,end);
        int i = start+length;
        int j = end;
        long long count =0;
        int indexc = end;
        while(i>=start&&j>=start+length+1){
            if(data[i]>data[j]){
                aux[indexc--] = data[i--];
                count += j - (start+length);  //和标准归并排序不一样的就是我们在合并数组的时候计算逆序对数
            }
            else{
                aux[indexc--] = data[j--];
            }
        }
        while(i>=start){
            aux[indexc--] = data[i--];
        }
        while(j>=start+length+1){
            aux[indexc--] = data[j--];
        }
        i=start;
        while(i<=end)
            data[i++]= aux[i++];
        return count + left+right;
    }
};

猜你喜欢

转载自blog.csdn.net/harry_128/article/details/80114573