剑指Offer 51. 数组中的逆序对(归并排序)

class Solution {
    public int reversePairs(int[] nums) {
        int left = 0;
        int right = nums.length-1;
        int cnt=0;
        int[] tmp = new int[nums.length];
        Arrays.fill(tmp,0);
        cnt=MergeSort(left,right,nums,tmp);
        for(int i=0;i<=right;i++){
            System.out.print(nums[i]);   
        }
        return cnt;
    }

    public int MergeSort(int left,int right,int[]nums,int[]tmp){
        int cnt=0;
        if(left<right){

            int mid = left + (right-left)/2;
            cnt+=MergeSort(left,mid,nums,tmp);
            cnt+=MergeSort(mid+1,right,nums,tmp);
            cnt+= merge(left,mid,right,nums,tmp);
        }
        return cnt;
    }

    public int merge(int left,int mid,int right,int[]nums,int[] tmp){
        for(int i=left;i<=right;i++){
            tmp[i] = nums[i];
        }
        int i=left;
        int j=mid+1;
        int count=0;
        int k=left;
        while(i<=mid&&j<=right){
            if(tmp[i]<=tmp[j]){
                nums[k++] = tmp[i];
                i++;
            }
            else{
                nums[k++] = tmp[j];
                j++;count+=(mid-i+1);
            }
        }
        while(j<=right){
            nums[k++] = tmp[j];
            j++;
        }
        while(i<=mid){
            nums[k++] = tmp[i];
            i++;
        }
        return count;
    }

}

 

posted @ 2020-10-17 16:40  dlooooo  阅读(119)  评论(0编辑  收藏  举报