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

来源:互联网 发布:男生丁丁知乎 编辑:程序博客网 时间:2024/06/11 03:32
/** * 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;    }}

原创粉丝点击