簡體   English   中英

在Java中實現Comparable的堆

[英]Heap that implements Comparable in Java

我有一個充滿雙打的數組,我想將那些雙打保存在堆中。 問題是我需要記錄數組索引。

Double[] array = new Double[n]; //imagine it's filled with doubles

現在我有了一個PriorityQueue:

PriorityQueue<Integer> heap = new PriorityQueue<Integer>(); //Integer because it's an heap of indexes

我想將數組的每個元素添加到堆中,但是我想保留INDEX的記錄。 因此,假設我將索引0添加到堆中:

The heap stores 0, but uses array[0] to compare and sort it.
Not index 0 itself, that's just like a class index. Stores v but compares v.value

當我從堆中獲取值時:

Imagine I do heap.pull();
The heap returns me index 0, and then I will know the value is array[0].

我可以用可比的方式做到這一點嗎?

希望我能很好地理解您的問題。 嘗試運行以下示例。 看看您是否了解它,這是否是您要尋找的行為。

int n = 10;
final double[] arr = new double[n];
for (int i = 0; i < n; ++i) {
    arr[i] = Math.random() * 100;
}
PriorityQueue<Integer> queue = new PriorityQueue<>(n, new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        return (int) (arr[o1] - arr[o2]);
    }
});

for (int i = 0; i < n; ++i) {
    queue.add(i);
}

System.out.println(Arrays.toString(arr));
System.out.println(queue.toString());

請注意,當您向PriorityQueue添加意外內容時,這會很快導致OutOfBoundsException

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM