java_力扣493_翻转对_分治(困难)

力扣:https://leetcode.cn/problems/reverse-pairs/
题目:翻转对

可以参考另外一篇文章(关于分治法左右区间单调遍历应该如何设计) https://blog.****.net/2303_78983004/article/details/143695227?spm=1001.2014.3001.5501

class Solution {
    public static final int maxn=50001;
    public static int[] help=new int[maxn];
    public static void merge(int[] nums,int l,int m,int r){
        int  p=l,ll=l,mm=m+1;
        for(;ll<=m&&mm<=r;){
            help[p++]=nums[ll]<=nums[mm]?nums[ll++]:nums[mm++];
        }
        while(ll<=m){
            help[p++]=nums[ll++];
        }
        while(mm<=r){
            help[p++]=nums[mm++];
        }
        for(int i=l;i<=r;i++){
            nums[i]=help[i];
        }
    }
    public static int GetKey(int[] nums,int l,int r){
        if(l==r)return 0;
        int m=(l+r)>>1,res=0;
        res+=GetKey(nums,l,m);
        res+=GetKey(nums,m+1,r);
        for(int ll=l,mm=m+1;ll<=m&&mm<=r;mm++){
           
            while(ll<=m&&nums[ll]/2.0<=nums[mm]){
                ll++;
                
            }
            if(ll<=m)res+=m-ll+1;
        }
        merge(nums,l,m,r);
        return res;
    }
    public int reversePairs(int[] nums) {
        return GetKey(nums,0,nums.length-1);
    }
}
上一篇:深度学习之 LSTM


下一篇:Virtual Private Network 协议