On the reverse (25) in the array

topic

[In the array of two numbers, if a number is greater than the front behind the figures, the two numbers form a reverse pair. Enter an array, this array P. finds the total number of reverse pair P and outputs the result modulo 1000000007. I.e., the output P% 1000000007]
The input: 7564
Output: 5


1, analysis
(1), is to use brute force approach were compared with each element of the rear element, in this case time complexity is O ( n 2 ) O (n ^ 2) , not the best way, so the use of other methods. Such as: merge sort, while statistics on the number of reverse. This time complexity is O ( n l o g n ) O (nlogn)
(2), first the size of the original array is gradually decomposed into an array of 1, and then subjected to gradually merge. FIG follows
Here Insert Picture Description
(3), then between the two reverse statistic sub-arrays, as shown below:
Here Insert Picture Description
Here Insert Picture Description


2, the code

class Solution {
public:
    int InversePairs(vector<int> data) {
        int len=data.size();
        if(len<=1)
            return 0;
        vector<int> temp(len);
        // 需要将count声明为long,否则可能有溢出的错误
        long count=0;
        MergeSort(data,temp,0,len-1,count);
        return count%1000000007;
    }
    // count 用于统计最终的逆序对数
    void MergeSort(vector<int> &data,vector<int> &temp,int left,int right,long &count)
    {
        if(left<right)
        {
            int mid=left+(right-left)/2;
            MergeSort(data,temp,left,mid,count);
            MergeSort(data,temp,mid+1,right,count);
            Merge(data,temp,left,mid,right,count);
        }
    }
    
    void Merge(vector<int> &data,vector<int> &temp, int left,int mid,int right,long &count)
    {
        int i=mid;
        int j=right;
        int index=right-left;
        while(i>=left && j>mid)
        {
            if(data[i]>data[j])
            {
                temp[index--]=data[i--];
                count+=j-mid; //若前一个大于后一个则会有 j-mid 个逆序对
            }
            else
            {
                temp[index--]=data[j--];
            }
        }
        while(i>=left)
        {
            temp[index--]=data[i--];
        }
        while(j>mid)
        {
            temp[index--]=data[j--];
        }
        
        index=right-left;
        while(left<=right)
        {
            data[right--]=temp[index--];
        }
    }
};
Published 213 original articles · won praise 48 · views 110 000 +

Guess you like

Origin blog.csdn.net/Jeffxu_lib/article/details/104865484