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

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

归并排序

class Solution {
    int[] tmp;
    int res = 0;

    public int reversePairs(int[] nums) {
        tmp = new int[nums.length];
        mergeSort(nums, 0, nums.length - 1);
        return res;
    }

    void mergeSort(int[] nums, int l, int r){
        if(l >= r) return;
        int mid = l + r >> 1;
        mergeSort(nums, l, mid);
        mergeSort(nums, mid + 1, r);

        int i = l, j = mid + 1, k = l;
        while(i <= mid && j <= r){
            if(nums[i] > nums[j]){
                tmp[k++] = nums[j++];
                res += mid - i + 1;
            } 
            else tmp[k++] = nums[i++];
        }

        while(i <= mid) tmp[k++] = nums[i++];
        while(j <= r) tmp[k++] = nums[j++];

        for(i = l; i <= r; i++) nums[i] = tmp[i];
    }
}

你可能感兴趣的:(#,剑指offer,算法)