繁体   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