在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
示例 1:
输入: [7,5,6,4]
输出: 5
限制:
0 <= 数组长度 <= 50000
题解
利用归并排序的局部有序,就可以批量知道左右的大小关系。
如图,1小先走,则右边的全部比1大。所以只需要加上右边的就可以了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| public int reversePairs(int[] nums) { if (nums == null || nums.length < 2) { return 0; } int k = mergeSort(nums, 0, nums.length - 1); System.out.println(Arrays.toString(nums)); return k; }
private int mergeSort(int[] nums, int left, int right) {
if (left == right) return 0; int mid = (left + right) / 2; int leftCount = mergeSort(nums, left, mid); int rightCount = mergeSort(nums, mid+1, right);
return leftCount+rightCount+merger(nums, left, mid, right); }
private int merger(int[] nums,int left ,int mid,int right){
int[] temp = new int[right - left + 1]; int count = 0; int p1 = left; int p2 = mid + 1; int i = 0; while (p1 <= mid && p2 <= right) { if (nums[p1] <= nums[p2]) { temp[i++] = nums[p1++]; }else { temp[i++] = nums[p2++]; count += mid - p1 +1 ; }
}
while (p1 <= mid) { temp[i++] = nums[p1++]; }
while (p2 <= right) { temp[i++] = nums[p2++]; }
for (int j = 0; j < temp.length; j++) { nums[left + j] = temp[j]; } return count; }
|