题目链接:. - 力扣(LeetCode). - 备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。https://leetcode.cn/problems/shu-zu-zhong-de-ni-xu-dui-lcof/submissions/571702329/
代码:
class Solution {
private int[] tmp;
public int reversePairs(int[] record) {
if (record == null || record.length == 0) {
return 0;
}
tmp = new int[record.length];
return mergeSort(record, 0, record.length - 1);
}
// 归并排序函数
private int mergeSort(int[] record, int left, int right) {
if (left >= right) return 0; // 如果只有一个元素或没有元素,不存在逆序对
int mid = left + (right - left) / 2;
// 递归分治,分别计算左边和右边的逆序对
int count = mergeSort(record, left, mid) + mergeSort(record, mid + 1, right);
// 统计跨子数组的逆序对
int i = left, j = mid + 1, k = 0;
while (i <= mid && j <= right) {
if (record[i] <= record[j]) {
tmp[k++] = record[i++];
} else {
// record[i] > record[j],因此 (i, j) 是逆序对,并且 i 到 mid 都与 j 构成逆序对
tmp[k++] = record[j++];
count += mid - i + 1;
}
}
// 处理剩余的元素
while (i <= mid) tmp[k++] = record[i++];
while (j <= right) tmp[k++] = record[j++];
// 将排好序的部分拷贝回原数组
for (int l = 0; l < k; l++) {
record[left + l] = tmp[l];
}
return count;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] record = {9, 7, 5, 4, 6};
System.out.println(solution.reversePairs(record)); // 输出:8
}
}