数组中的逆序对
题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
思路
- 如果扫描整个数组,每个数字跟后面的数字比较大小,整体的复杂度是O(n^2)
- 可以利用归并排序的算法的思想,在排序的同时判断前后两个子序列中存在的逆序对,都是从后往前排,如果前面的数大于后面的数,因为都是已经排好序的所以前面的数一定比后面的数都大,逆序对为后面剩下的元素的数量,然后正常排序;若小于,则这个元素不产生逆序对,正常排序。时间复杂度是O(nlogn)
代码
public class Solution {
public int InversePairs(int [] array) { if (array == null || array.length == 0) { return 0; } int[] copy = new int[array.length]; for (int i = 0; i < array.length; i++) { copy[i] = array[i]; } int count = inverseCore(array, copy, 0, array.length - 1); return count; } public int inverseCore(int[] data, int[] copy, int start, int end) { if (start == end) { copy[start] = data[start]; return 0; } int length = (end - start) / 2; int left = inverseCore(copy, data, start, start + length); int right = inverseCore(copy, data, start + length + 1, end); int i = start + length; int j = end; int indexCopy = end; int count = 0; while (i >= start && j >= start + length + 1) { if (data[i] > data[j]) { copy[indexCopy--] = data[i--]; count += j - (start + length); } else { copy[indexCopy--] = data[j--]; } } for (; i >= start; i--) { copy[indexCopy--] = data[i]; } for (; j >= start+length+1; j--) { copy[indexCopy--] = data[j]; } return count + left + right; } }