分治逆序对计数java实现
时间: 2023-10-22 17:28:11 浏览: 83
以下是基于Java语言的分治逆序对计数算法实现:
```java
public class ReversePairs {
public static int reversePairs(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int[] temp = new int[nums.length];
return mergeSort(nums, 0, nums.length - 1, temp);
}
private static int mergeSort(int[] nums, int left, int right, int[] temp) {
if (left >= right) {
return 0;
}
int mid = left + (right - left) / 2;
int invLeft = mergeSort(nums, left, mid, temp);
int invRight = mergeSort(nums, mid + 1, right, temp);
int invMerge = merge(nums, left, mid, right, temp);
return invLeft + invRight + invMerge;
}
private static int merge(int[] nums, int left, int mid, int right, int[] temp) {
int i = left, j = mid + 1, k = left;
int invCount = 0;
while (i <= mid && j <= right) {
if (nums[i] <= nums[j]) {
temp[k++] = nums[i++];
} else {
temp[k++] = nums[j++];
invCount += mid - i + 1;
}
}
while (i <= mid) {
temp[k++] = nums[i++];
}
while (j <= right) {
temp[k++] = nums[j++];
}
for (i = left; i <= right; i++) {
nums[i] = temp[i];
}
return invCount;
}
}
```
其中,reversePairs函数是算法的入口,用于对数组nums进行逆序对计数,返回总的逆序对数量。mergeSort函数是递归函数,用于将原数组分成左右两个子数组进行处理;merge函数用于将左右两个子数组合并成一个有序的数组,并计算左右两个子数组之间的逆序对数量。整个算法的时间复杂度为O(nlogn)。
阅读全文