Java 21默认开大内存
很容易遇到
所以如果换成Java 8
最后一个我也不知道为啥,有大佬帮忙看一下吗
import java.util.*;
public class Main {
static Scanner cin = new Scanner(System.in);
// 非递归版本的归并排序,返回逆序对的数量
public static long mergeAndCount(long[] arr) {
int n = arr.length;
long count = 0;
long[] temp = new long[n];
// 分治排序的步长从1开始,一步一步增大
for (int size = 1; size < n; size *= 2) {
for (int left = 0; left < n - size; left += 2 * size) {
int mid = Math.min(left + size - 1, n - 1);
int right = Math.min(left + 2 * size - 1, n - 1);
count += merge(arr, temp, left, mid, right);
}
}
return count;
}
// 合并两个已排序的子数组并计算逆序对
public static long merge(long[] arr, long[] temp, int left, int mid, int right) {
int i = left, j = mid + 1, k = left;
long count = 0;
// 归并排序
while (i <= mid && j <= right) {
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
count += (mid - i + 1); // 计算逆序对
}
}
// 复制剩余的元素
while (i <= mid) {
temp[k++] = arr[i++];
}
while (j <= right) {
temp[k++] = arr[j++];
}
// 将合并后的元素拷贝回原数组
System.arraycopy(temp, left, arr, left, right - left + 1);
return count;
}
public static void main(String[] args) {
int n = cin.nextInt();
long[] arr = new long[n];
// 输入数组
for (int i = 0; i < n; i++) {
arr[i] = cin.nextLong();
}
// 计算逆序对的数量
long result = mergeAndCount(arr);
// 输出结果
System.out.println(result);
}
}