1 问题描述
在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对,输入一个数组,求出这个数组中的逆序对的总数。
例如在数组{7, 5, 6, 4}中,一共存在5个逆序对,分别是{7, 5}, {7, 6}, {7, 4}, {5, 4}, {6, 4}
2 解决思路
如果按照顺序扫描的方式,则复杂度为O(n2),不符合要求,而归并排序的策略可以完成,归并时从大到小进行归并,一旦左边部分的数字比右边部分的数字大,那么就可以累积逆序对的数目。
public static int inversCount(int[] array, int start, int end) {
if (start == end) {
return 0;
}
int len = (end - start) / 2;
int leftCount = inversCount(array, start, start + len);
int rigthCount = inversCount(array, start + len + 1, end);
int count = 0;
int i = start + len;
int j = end;
int length = end - start;
int[] temp = new int[length + 1];
while (i >= start && j >= start + len + 1) {
if (array[i] > array[j]) {
count += j - start - len; //统计逆序对数目
temp[length--] = array[i--];
} else {
temp[length--] = array[j--];
}
}
while (i >= start) {
temp[length--] = array[i--];
}
while (j >= start + len + 1) {
temp[length--] = array[j--];
}
length = end - start + 1;
for(int x = 0; x < length; x++) {
array[start++] = temp[x];
}
return count + leftCount + rigthCount;
}
public static void main(String[] args) {
int[] array = {9, 1, 2, 5, 4};
System.out.println("inversCount: " + inversCount(array, 0 ,array.length - 1));
}
运行结果
inversCount: 5