/**
* 题目:数组中的逆序对。
* 在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。
* 输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。
* 即输出P%1000000007。例如输入{1,2,3,4,5,0},输出5对。
* 并返回它的位置,如果没有则返回 -1(需要区分大小写)。
* @author hexiaoli
* 思路:剑指offer
* 大神博客:
* 作者:Fan0628 来源:CSDN 原文:https://blog.csdn.net/Fan0628/article/details/88965141
* 版权声明:本文为博主原创文章,转载请附上博文链接!
* 分治思想,采用归并排序的思路来处理。在合并两个有序序列时,同时计算逆序对数。
* 对于两个升序序列,设置两个下标:两个有序序列的末尾。
* 每次比较两个末尾值,如果前末尾大于后末尾值,则有“后末尾指针减中间值”个逆序对,
* 并移动后末尾指针;否则不构成逆序对,向前移动前末尾指针。
* 然后把较大值拷贝到辅助数组(即合并完的升序序列)的末尾。
* 每次在合并前,先递归地处理左半段、右半段,则左、右半段有序,且左右半段的逆序对数量可得,再计算左右半段合并时逆序对的个数。
* 逆序对的总数=左边数组中的逆序对的数量+右边数组中逆序对的数量+左右结合成新的顺序数组时出现的逆序对数量。
*/
public class Main {
public static int inversePairs(int[] array) {
//边界
if(array == null ||array.length == 0) {
return 0;
}
int[] copyArray = new int[array.length];
for (int i = 0; i < array.length; i++) {
copyArray[i]=array[i];
}
int count = inversePairsCore(array, copyArray, 0, array.length - 1);
return count;
}
public static int inversePairsCore(int[] array,int[] copyArray,int head,int tail) {
if(head == tail) {
return 0;
}
//mid位置
int mid = (head+tail)>>1;
// 递归,分别计算左边和右边内部的逆序对个数
int leftCount = inversePairsCore(array, copyArray, head, mid) % 1000000007;
int rightCount = inversePairsCore(array, copyArray, mid + 1, tail) % 1000000007;
// count计数左右两者之间的对数
int count = 0;
// i指向mid,j指向tail
int i = mid;
int j = tail;
// 临时数组的指针,指向tail
int tempCopy = tail;
while (i>=head && j>mid) {
// 如果arr[i]大于arr[j]
if (array[i] > array[j]) {
// i指向的数大于右半部分所有的数,计数加入j-mid
count += j - mid;
// 临时数组存放i指向的数,同时tempCopy和i都向前移动
copyArray[tempCopy--] =array[i--];
//防止count过大
if (count >= 1000000007) {
count %= 1000000007;
}
}else {// 如果arr[i]小于arr[j],tempCopy和j都向前移动
copyArray[tempCopy--] = array[j--];
}
}
// 移动完之后将没存放的数字存入临时数组,例如[1,2,3,4][5,6,7,8],
// 临时数组存完后面四个[5,6,7,8],j移动到mid移动终止,将剩下的[1,2,3,4]存入临时数组
for (; i >= head; i--) {
copyArray[tempCopy--] = array[i];
}
// 同理,这也是移动完之后将没存放的数字存入临时数组,例如[5,6,7,8][1,2,3,4],
// 临时数组存完后面四个[5,6,7,8],i移动到head移动终止,将剩下的[1,2,3,4]存入临时数组
for (; j > mid; j--) {
copyArray[tempCopy--] = array[j];
}
// 将临时数组复制到原数组,以便递归
System.arraycopy(copyArray, head, array, head, tail - head + 1);
return (leftCount + rightCount + count) % 1000000007;
}
public static void main(String[] args) {
int[] array = new int[]{7,5,6,4};
System.out.println(inversePairs(array));
}
}