zoukankan      html  css  js  c++  java
  • [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; 
        }
    }
    
  • 相关阅读:
    no space left on device
    功能测试用例
    数据库命令
    移动APP测试用例设计实践经验(转载)
    15个常用sql命令
    将Windows文件夹挂载到Linux上
    英语学习方法
    三种特质 做领导
    扬州之行 第一天
    list、dict、str虽然是Iterable,却不是Iterator
  • 原文地址:https://www.cnblogs.com/coding-gaga/p/13884177.html
Copyright © 2011-2022 走看看