【剑指Offer】数组中的逆序对 Posted on 2017-08-31 | In Algorithm , 剑指Offer 题目在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对,输入一个数组,求出这个数组中的逆序对的总数。 实现123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051public int InversePairs(int[] array) { if (array == null || array.length < 1) return 0; int[] aux = new int[array.length]; for (int i = 0; i < array.length; i++) aux[i] = array[i]; return sortAndCount(array, aux, 0, array.length - 1);}private int sortAndCount(int[] array, int[] aux, int start, int end){ if (start == end) return 0; int mid = (start + end) / 2; int leftCount = sortAndCount(array, aux, start, mid); int rightCount = sortAndCount(array, aux, mid + 1, end); int splitCount = countSplitInv(array, aux, start, mid, end); return (leftCount + rightCount + splitCount) % 1000000007;}private int countSplitInv(int[] array, int[] aux, int start, int mid, int end) { int count = 0; int j = start; int k = mid + 1; for (int i = start; i <= end; i++) { if (j > mid) array[i] = aux[k++]; else if (k > end) array[i] = aux[j++]; else if (aux[j] < aux[k]) array[i] = aux[j++]; else { count += mid - j + 1; array[i] = aux[k++]; if (count > 1000000007) count %= 1000000007; } } for (int i = start; i <= end; i++) aux[i] = array[i]; return count;}