剑指 Offer 51. 数组中的逆序对

class Solution {
public:
    vector<int> temp;
    int res = 0;

    int reversePairs(vector<int>& nums) {
        int n = nums.size();
        temp.resize(n);

        mergeSort(nums, 0, n - 1);
        return res;
    }

    void mergeSort(vector<int>& nums, int l, int r) {
        if (l < r) {
            int mid = l + r >> 1;
            mergeSort(nums, l, mid);
            mergeSort(nums, mid + 1, r);
            merge(nums, l, r);
        }
    }
    
    void merge(vector<int>& nums, int l, int r) {
        int mid = l + r >> 1;
        int i = l, j = mid + 1, k = 0;
        while (i <= mid && j <= r) {
            if (nums[i] <= nums[j]) {
                temp[k++] = nums[i++];
            } else {
                res += mid - i + 1;
                temp[k++] = nums[j++];
            }
        }
        
        while (i <= mid) temp[k++] = nums[i++];
        while (j <= r) temp[k++] = nums[j++];
        
        for (int i = 0; i < k; i++)
            nums[l + i] = temp[i];
    }
};
posted @ 2021-07-31 20:25  Dazzling!  阅读(25)  评论(0编辑  收藏  举报