【问题标题】:Priority Queue<Integer>=k ,does not remove the k where distance[k] is minPriority Queue<Integer>=k ,不移除距离 [k] 为 min 的 k
【发布时间】:2021-05-20 07:36:41
【问题描述】:
int[] distance = new int[100];
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        if (distance[o1] > distance[o2] ) {
            return -1;
        } else if (distance[o1] < distance[o2] ) {
            return 1;
        }
        return 0;
    }
});


for (int i = 0; i < 100; i++) {
    distance[i] =new Random().nextInt(100)+1;
    pq.add(i);
}

distance[10]=0;
int u=pq.poll();

我认为这个比较器应该返回距离 [k]=MinimumDistance 的元素 k。 无法理解为什么这不起作用.. pq.Poll 它不是基于 distance[] 数组。 例如这里的变量 u 应该是 10。

【问题讨论】:

  • 欢迎来到 SO! PriorityQueue的具体实现是什么?是您创建的自定义类(在这种情况下,请将其源代码添加到问题中)还是某些第三方的实现?在这种情况下添加包,指定您使用的第三方 jar 的版本并考虑更新问题中的标签,以便最相关的人可以跟踪此问题

标签: java priority-queue


【解决方案1】:

两个问题:你的比较是相反的。应该是

if (distance[o1] > distance[o2] ) {
    return 1;
} else if (distance[o1] < distance[o2] ) {
    return -1;
}

其次,您必须在循环之前设置距离[10]=0,然后不要覆盖它。此比较器仅在添加内容时起作用,然后您在位置 10 处有一个随机数。

【讨论】:

  • 谢谢,我认为 PriorityQueue 会在即将删除时自行更新。
猜你喜欢
  • 2012-10-31
  • 2020-06-14
  • 2013-04-22
  • 2015-06-02
  • 1970-01-01
  • 1970-01-01
  • 2020-02-09
  • 2014-03-04
  • 1970-01-01
相关资源
最近更新 更多