LeetCode493. Reverse Pairs

版权声明:本文为博主原创文章,欢迎转载!转载请保留原博客地址。 https://blog.csdn.net/grllery/article/details/88915760

493. Reverse Pairs

Given an array nums, we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j].

You need to return the number of important reverse pairs in the given array.

Example1:

Input: [1,3,2,3,1]
Output: 2

Example2:

Input: [2,4,3,5,1]
Output: 3

Note:

The length of the given array will not exceed 50,000.
All the numbers in the input array are in the range of 32-bit integer.


题目:给定数组nums,如果i < j, 并且nums[i] > 2*nums[j],那么我们称nums[i]nums[j]为重要的逆序对important reverse pairs。返回逆序对的数目。

思路:参见General principles behind problems similar to “Reverse Pairs”。先递归拆分成若干个子数组,然后再合并成有序的数组,在合并的过程中计算左右数组对应的满足条件的逆序对的个数。即在归并排序中的并过程计算目标数。

工程代码下载

class Solution {
public:
    int reversePairs(vector<int>& nums) {
        return reversePairs(nums, 0, nums.size() - 1);
    }
private:
    int reversePairs(vector<int>& nums, int l ,int r){
        if(l >= r)
            return 0;

        int m = l + (r - l) / 2;
        int res = reversePairs(nums, l, m) + reversePairs(nums, m+1, r);

        int i = l, j = m + 1, k = 0,  p = m + 1;
        vector<int> merge(r - l + 1);

        while(i <= m){
            while(p <= r && nums[i] > 2L * nums[p]){
                ++p;
            }
            res += p - (m + 1);

            while(j <= r && nums[i] > nums[j]){
                merge[k++] = nums[j++];
            }

            merge[k++] = nums[i++];
        }

        while(j <= r)
            merge[k++] = nums[j++];

        copy(merge.begin(), merge.end(), nums.begin() + l);

        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/grllery/article/details/88915760