请问我用归并,有些测试样例爆内存溢出

P1908 逆序对

thebestsun @ 2024-02-20 20:45:35

这是代码
import java.util.Scanner;
public class Main {
    static int N =500010;
    static int[] nums = new int[N];
    static int[] temp = new int[N];
    static long sum = 0;
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        for (int i = 0; i <n ; i++) {
            nums[i] = scanner.nextInt();
        }
        merge_sort(nums,0,n-1);
        System.out.println(sum);
    }
    static void merge_sort(int[] q,int l,int r){
        if (l>=r){
            return ;
        }
        int mid = l+r>>1;
        merge_sort(q,l,mid);
        merge_sort(q,mid+1,r);

        int k = 0, i = l, j = mid+1;
        while (i<=mid&&j<=r){
            if (nums[i]<=nums[j]) temp[k++] = nums[i++];
            else {
                temp[k++] = nums[j++];
                sum += mid-i+1;
            }
        }
        while (i<=mid) temp[k++] = nums[i++];
        while (j<=r) temp[k++] = nums[j++];

        for (k = 0, i = l; i <= r; i++,k++){
            nums[i] = temp[k];
        }
    }
}

|