剑指Offer第36题—Java版

本题使用归并排序的思想,结合归并排序,写出的算法解。

 

//数组中的逆序对
public static int InversePairs(int[] array){
    if(array==null||array.length<=1)
        return 0;
    int[] copy = new int[array.length];
    //复制原数组
    copy = Arrays.copyOf(array, array.length);
    return mergeCount(array, copy, 0, array.length-1);
}

public static int mergeCount(int[] array, int[] copy, int start, int end){
    if(start==end){
        copy[start] = array[start];
        return 0;
    }
    int mid = (start+end)>>1;
    int leftCount = mergeCount(copy, array, start, mid);
    int rightCount = mergeCount(copy, array, mid+1, end);
    
    //计算两个已经求解好的数组的逆序对
    int i = mid;//i初始化为前半段最后一个数字的下标
    int j = end;//j初始化为后半段最后一个数字的下标
    //作为复制到临时数组的下标
    int index = end;//辅助数组复制的数组的最后一个数字的下标
    //计算两个数组在合并过程中的逆序对数
    int count = 0;//计数--逆序对的数目
    while(i>=start&&j>=mid+1){
        if(array[i]>array[j]){
        	//copy数组存放排序好的数,
            copy[index--] = array[i--];
            count += j-mid;
        }else{
            copy[index--] = array[j--];
        }
    }
    //把左边剩下的放到copy数组
    for(;i>=start;i--){
        copy[index--] = array[i];
    }
    //把右边剩下的放到copy数组
    for(;j>=mid+1;j--){
        copy[index--] = array[j];
    }
    //返回的是某一边的数
    return leftCount+rightCount+count;
}


 

转载于:https://www.cnblogs.com/loren-Yang/p/7466140.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值