[英]Java PriorityQueue Comparator to insert a 2D array under certain conditions
我有一個二維數組arr= [[1,4],[4,4],[2,2],[3,4],[1,1]]
我想將其放入 PriorityQueue 中,使其按以下順序存儲: [[1,1],[2,2],[1,4],[3,4],[4,4 ]]
IE
如果兩個數組的第一個元素相同,則應首先出現第二個元素值較低的元素
如果兩個數組的第二個元素相同,則應首先出現第一個元素值較低的元素
否則第二個元素的值較低的應該首先出現
我嘗試了以下代碼:
import java.io.*;
import java.util.*;
class Check2
{
public static void main(String[] args) {
int events[][]={{1,4},{4,4},{2,2},{3,4},{1,1}};
PriorityQueue<int[][]> min_heap= new PriorityQueue<int[][]>(events ,new Comparator<Integer>()
{
@Override
public int compare(int a[][], int b[][])
{
int res=-1;
if(a[0][1]==b[0][1])
{
if(a[0][0]>b[0][0])
res=-1;
else
res=1;
}
else
{
if(a[0][1]>b[0][1])
res=-1;
else
res=1;
}
}
}
);
}
}
我收到以下錯誤:
Check2.java:8: error: <anonymous Check2$1> is not abstract and does not override abstract method compare(Integer,Integer) in Comparator
{
^
Check2.java:9: error: method does not override or implement a method from a supertype
@Override
^
Check2.java:7: error: incompatible types: int[][] cannot be converted to int
PriorityQueue<int[][]> min_heap= new PriorityQueue<int[][]>(events ,new Comparator<Integer>()
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
3 errors
我知道比較功能在這里不適用於二維數組,但是我該如何獲得結果。
我嘗試通過到處檢查來實施其他技術,但沒有奏效。 請幫忙。
排隊
PriorityQueue<int[][]> min_heap= new PriorityQueue<int[][]>(events ,new Comparator<Integer>()
您提供集合作為第一個參數,但PriorityQueue
沒有這樣的構造函數。 您不能在一個構造函數中提供比較器和集合。
而且您仍然不需要在PriorityQueue
中存儲int[][]
來解決這個問題,而是存儲int[]
。
public static void main(String[] args) {
int[][] events ={{1,4},{4,4},{2,2},{3,4},{1,1}};
PriorityQueue<int[]> min_heap = new PriorityQueue<>((x, y) -> {
if(x[0] != y[0]) {
return Integer.compare(x[0], y[0]);
}
if(x[1] != y[1]) {
return Integer.compare(x[1], y[1]);
}
return 0;
});
min_heap.addAll(Arrays.asList(events));
while(min_heap.peek() != null) {
System.out.println(Arrays.toString(min_heap.poll()));
}
}
輸出:
[1, 1]
[1, 4]
[2, 2]
[3, 4]
[4, 4]
我有一種不同的方法來解決這種情況。 第一的,
Arrays.sort(events, Comparator.comparingInt(e -> e[0]));
PriorityQueue<int[]> minHeap = new PriorityQueue<>(events.length);
minHeap.addAll(Arrays.asList(events));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.