【问题标题】:Does java have an indexed minimum priority queue?java有索引的最低优先级队列吗?
【发布时间】:2012-05-07 23:01:25
【问题描述】:

我需要它来实现 Dijkstra 算法,而且我确实有自己的实现,但是使用 java 自己的类来记录我的代码会更容易。

【问题讨论】:

标签: java priority-queue shortest-path dijkstra


【解决方案1】:

不,Java 标准库没有这样的数据结构。 我想大多数人都使用这个: http://algs4.cs.princeton.edu/24pq/IndexMinPQ.java.html

【讨论】:

  • 最好提供一个简短的信息,因为将用户导航到链接以获取更多信息,好像链接断开,答案是没有用的。
  • @cohadar:TreeMap 呢?它提供在 O(log(n)) 时间内删除任意对象(可以被视为索引访问)。
【解决方案2】:

如果我们想更新java中优先级队列中现有键的值。也许我们可以使用 remove 方法然后插入具有不同值的相同键。这里删除并提供将花费 log(n) 时间。

示例代码如下:

    static class Edge {
        int vertex;
        int weight;
        public Edge(int vertex, int weight) {
            this.vertex = vertex;
            this.weight = weight;
        }
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Edge other = (Edge) obj;
            if (weight != other.weight)
                return false;
            if (vertex != other.vertex)
                return false;
            return true;
        }
    }
    
    public static void main(String[] args) {
        Edge record1 = new Edge(1, 2);
        Edge record2 = new Edge(4, 3);
        Edge record3 = new Edge(1, 1);//this record3 key is same as record1 but value is updated
        PriorityQueue<Edge> queue = new PriorityQueue<>((a, b) -> a.weight - b.weight);
        queue.offer(record1 );
        queue.offer(record2);//queue contains after this line [Edge [vertex=1, weight=2], Edge [vertex=4, weight=3]]
        Edge toBeUpdatedRecord = new Edge(1, 2);//this is identical to record1
        queue.remove(toBeUpdatedRecord);// queue contains after this line [Edge [vertex=4, weight=3]]
        queue.offer(record3);//Finally can see updated value for same key 1 [Edge [vertex=1, weight=1], Edge [vertex=4, weight=3]]
   }

【讨论】:

    【解决方案3】:

    “索引”是什么意思? 优先队列不支持索引,除非它不再排队。

    Java 支持标准优先级队列,如 C++ STL。 它可以在 java.util 命名空间中找到 PriorityQueue

    【讨论】:

    • Quote : 在许多应用程序中,允许客户端引用已经在优先级队列中的项目是有意义的。一种简单的方法是将唯一的整数索引与每个项目相关联。 我已经有一个实现,但是如果我可以使用 Java 类而不是为我的实现制作完整的文档,那就太棒了.
    • @hexct indexed 并不意味着它允许索引访问。索引是与队列元素相关联的唯一整数。就像队列元素的唯一整数值​​一样。 Robert Sedgewick 在他的《算法》一书中进行了很好的介绍。
    • @Fatso 引用什么?
    猜你喜欢
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多