java中整数数组的优先级队列

Suh*_*esh 8 java heap priority-queue min-heap

我想比较以下数组的第二个元素:

int[][] intervals = new int[][]{new int[]{0, 30},new int[]{5, 10},new int[]{15, 20}};
Run Code Online (Sandbox Code Playgroud)

我的优先级队列与自定义比较器:

PriorityQueue<int[]> heap = new PriorityQueue(intervals.length, (a, b) -> a[1] - b[1]);
Run Code Online (Sandbox Code Playgroud)

但我收到以下 2 个错误:

Line 8: error: array required, but Object found
        PriorityQueue<Integer[]> heap = new PriorityQueue(intervals.length, (a, b) -> a[1] - b[1]);
                                                                                       ^
Line 8: error: array required, but Object found
        PriorityQueue<Integer[]> heap = new PriorityQueue(intervals.length, (a, b) -> a[1] - b[1]);
                                                                                             
Run Code Online (Sandbox Code Playgroud)

小智 6

您应该首先将 a 转换为 int 数组。

PriorityQueue<int[]> heap = new PriorityQueue(intervals.length, (a, b) -> ((int[])a)[1] - ((int[])b)[1]);
Run Code Online (Sandbox Code Playgroud)


Mar*_*ein 5

您可以使用 Integer.compare

PriorityQueue<int[]> heap = new PriorityQueue<>(intervals.length, (a,b) -> Integer.compare(a[1],b[1]));
Run Code Online (Sandbox Code Playgroud)