剑指offer-面试题36-数组中的逆序对

/**
 * Created by apple on 17/6/2.
 * 求数组中的逆序对数,时间复杂度为O(nlogn)
 */
public class InversePairs {
    public static void main(String[] args) {
        int[] arr = {7, 4, 5, 6, 1, 2};
        System.out.println("排序之前的数组:");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
        System.out.println("逆序对数为:" + getInversePairs(arr));

        System.out.println("排序之后的数组:");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }

    }

    /**
     * 获取逆序对数量,通过归并的方法,时间复杂度O(nlogn)
     *
     * @param arr,带查找的逆序对的数组
     * @return arr中逆序对的个数
     */
    public static int getInversePairs(int[] arr) {
        if (arr == null || arr.length <= 0) {
            return -1;
        }

        return getInversePairsCore(arr, 0, arr.length - 1);
    }

    private static int getInversePairsCore(int[] arr, int low, int high) {
        if (low >= high) {
            return 0;
        }
        int middle = (low + high) / 2;
        int left = getInversePairsCore(arr, low, middle);
        int right = getInversePairsCore(arr, middle + 1, high);
        int count = getTwoArrPairs(arr, low, middle, high);
        return left + right + count;
    }

    private static int getTwoArrPairs(int[] arr, int low, int middle, int high) {
        int[] copy = new int[arr.length];
        int index = high;
        int countPairs = 0;
        int endL = middle;
        int endR = high;
        //统计左数组和右数组的逆序对数,并拼接
        while (low <= endL && middle + 1 <= endR) {
            if (arr[endL] > arr[endR]) {
                countPairs += endR - middle;
                copy[index--] = arr[endL--];
            } else if (arr[endL] <= arr[endR]) {
                copy[index--] = arr[endR--];
            }
        }
        //拼接剩余的数
        while (endR >= middle + 1) {
            copy[index--] = arr[endR--];
        }
        while (endL >= low) {
            copy[index--] = arr[endL--];
        }
        //修改原数组
        for (int i = low; i <= high; i++) {
            arr[i] = copy[i];
        }
        //返回两个数组的逆序对数
        return countPairs;
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值