美文网首页面试算法
牛客-剑指0ffer-数组中的逆序对

牛客-剑指0ffer-数组中的逆序对

作者: wenyilab | 来源:发表于2019-08-06 08:32 被阅读10次

题目描述

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数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

class Solution {
public:
    int InversePairs(vector<int> data) {
        if (data.size() == 0){
            return 0;
        }
        vector<int> copy(data);
        return InversePairsCores(data,copy,0,data.size()-1);
    }
    int InversePairsCores(vector<int>& data,vector<int>& copy,int begin,int end){
        if (begin == end){
            return 0;
        }
        int mid = begin + (end - begin) / 2;
        int left = InversePairsCores(copy,data,begin,mid);
        int right = InversePairsCores(copy,data,mid+1,end);
        
        int last_in_left = mid;
        int last_in_right = end;
        int index_copy = end;
        long res = 0;
        
        while (last_in_left >= begin && last_in_right >= mid + 1){
            if(data[last_in_left] > data[last_in_right]){
                copy[index_copy--] = data[last_in_left--];
                res += last_in_right - mid;
                
            }else{
                copy[index_copy--] = data[last_in_right--];
                
            }
        }
        while (last_in_left >= begin){
            copy[index_copy--] = data[last_in_left--];

        }
        while(last_in_right >= mid+1){
            copy[index_copy--] = data[last_in_right--];

        }
        return (left+right+res) % 1000000007;
        
    }
};

相关文章

网友评论

    本文标题:牛客-剑指0ffer-数组中的逆序对

    本文链接:https://www.haomeiwen.com/subject/pvvbdctx.html