【LeetCode-493】翻转对

问题

给定一个数组 nums ,如果 i < j 且 nums[i] > 2*nums[j] 我们就将 (i, j) 称作一个重要翻转对。

你需要返回给定数组中的重要翻转对的数量。

示例

输入: [1,3,2,3,1]
输出: 2

解答

class Solution {
public:
    int reversePairs(vector<int>& nums) {
        tmp.resize(nums.size());
        mergeSort(nums, 0, nums.size() - 1);
        return res;
    }
private:
    vector<int> tmp;
    int res = 0;
    void mergeSort(vector<int>& nums, int left, int right) {
        if (left >= right) return;
        int mid = left + (right - left) / 2;
        mergeSort(nums, left, mid);
        mergeSort(nums, mid + 1, right);
        // ------ 与归并排序的区别
        int ii = left, jj = mid + 1;
        while (ii <= mid && jj <= right) {
            if (nums[ii] <= 2 * (long)nums[jj]) ii++;
            else {
                res += mid - ii + 1;
                jj++;
            }
        }
        // ------
        int i = left, j = mid + 1, cnt = left;
        while (i <= mid && j <= right) {
            if (nums[i] <= nums[j]) tmp[cnt++] = nums[i++];
            else tmp[cnt++] = nums[j++];
        }
        while (i <= mid) tmp[cnt++] = nums[i++];
        while (j <= right) tmp[cnt++] = nums[j++];
        for (int i = left; i <= right; i++) nums[i] = tmp[i];
    }
};

重点思路

参考【剑指Offer-51】数组中的逆序对

posted @ 2021-03-05 22:37  tmpUser  阅读(38)  评论(0编辑  收藏  举报