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

来源:互联网 发布:淘宝卖的哈曼卡顿真假 编辑:程序博客网 时间:2024/05/21 13:23

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

思路:链接:归并排序启发得来,把数据分成前后两个数组(递归分到每个数组仅有一个数据项),合并数组,合并时,从后往前遍历,出现前面的数组值array[i]大于后面数组值array[j]时,则,array[i]大于array[start + center + 1] 到array[i]中的所有数。

class Solution {public:    int InversePairs(vector<int> data) {        int length = data.size();        if(length < 1)            return 0;        vector<int> copy(data);        return InversePairsCore(copy,data,0,length - 1);    }        int InversePairsCore(vector<int> &copy,vector<int> &data,int start, int end){        if(start == end)            return 0;        int center = (end - start) / 2;                int left = InversePairsCore(copy,data,start,start + center)%1000000007;        int right = InversePairsCore(copy,data,start + center + 1,end)%1000000007;                int i = start + center;        int j = end;        int copyIndex = end;        int count = 0;                while(i >= start && j >= start + center + 1){            if(data[i] > data[j]){                copy[copyIndex--] = data[i--];                count += j - start -center;                if(count > 1000000007)                    count %= 1000000007;            }else{                copy[copyIndex--] = data[j--];            }        }                while(i >= start)            copy[copyIndex--] = data[i--];        while(j >= start + center + 1)            copy[copyIndex--] = data[j--];                for(int k = start; k <= end; k++)            data[k] = copy[k];                return (left + right + count)%1000000007;    }


阅读全文
0 0