[LeetCode]归并排序、剑指 Offer 51. 数组中的逆序对(普通解法版-开临时数组)

归并排序

代码

package Offer;

public class mergeSort {
	public static void main(String[] args) {
		int[] nums = new int[] { 1, 3, 2, 3, 1, -1, 100 };
		mergeSort(nums, 0, nums.length - 1);
		for (int num : nums) {
			System.out.println(num);
		}
	}

	public static void mergeSort(int[] nums, int l, int r) {
		if (l == r) {
			return;
		}
		int mid = l + (r - l) / 2;
		mergeSort(nums, l, mid);
		mergeSort(nums, mid + 1, r);

		int i = l;
		int j = mid + 1;
		int[] tmp = new int[r - l + 1];
		int mergeIdx = 0;
		while (i <= mid && j <= r) {
			if (nums[i] <= nums[j]) {
				tmp[mergeIdx++] = nums[i++];
			} else {
				tmp[mergeIdx++] = nums[j++];
			}
		}
		while (i <= mid) {
			tmp[mergeIdx++] = nums[i++];
		}
		while (j <= r) {
			tmp[mergeIdx++] = nums[j++];
		}

		mergeIdx = 0;
		for (int k = l; k <= r; ++k) {
			nums[k] = tmp[mergeIdx++];
		}
	}
}

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

代码

class Solution {
    public int reversePairs(int[] nums) {
        if(nums.length==0){
            return 0;
        }

        int[] copyNums=new int[nums.length];
        for(int i=0;i<nums.length;++i){
            copyNums[i]=nums[i];
        }

        int reverseCnt=getReverseCnt(copyNums,0,nums.length-1);
        return reverseCnt;
    }

    public int getReverseCnt(int[] nums,int l,int r){
        if(l==r){
            return 0;
        }

        int mid=l+(r-l)/2;
        int lRevCnt=getReverseCnt(nums,l,mid);
        int rRevCnt=getReverseCnt(nums,mid+1,r);

        int i=l;
        int j=mid+1;
        int[] tmpArr=new int[r-l+1];
        int mergeIdx=0;
        int revCnt=0;
        while(i<=mid&&j<=r){
            if(nums[i]<=nums[j]){
                tmpArr[mergeIdx++]=nums[i++];
            }else{
                revCnt+=mid+1-i;
                tmpArr[mergeIdx++]=nums[j++];
            }
        }
        while(i<=mid){
            tmpArr[mergeIdx++]=nums[i++];
        }
        while(j<=r){
            tmpArr[mergeIdx++]=nums[j++];
        }

        mergeIdx=0;
        for(int k=l;k<=r;++k){
            nums[k]=tmpArr[mergeIdx++];
        }
        return revCnt+lRevCnt+rRevCnt; 
    }
}

posted on 2020-10-27 12:40  coding_gaga  阅读(57)  评论(0编辑  收藏  举报

导航