【问题标题】:Time complexity (Big-O) of merging two PriorityQueues合并两个 PriorityQueue 的时间复杂度(Big-O)
【发布时间】:2021-03-13 15:01:14
【问题描述】:

来自PriorityQueue Javadoc

实施说明:此实施提供 O(log(n)) 时间用于入队和出队方法 offerpollremove()addremove(Object)contains(Object) 的线性时间 方法;检索方法的恒定时间 peekelementsize

所以,我的问题是,O(log(n)) 时间复杂度坚持 是否可以将PriorityQueues 合并为一个?还是考虑插入 O(nlog(n)) ?如果合并更多堆,这种情况会改变吗?

这些PriorityQueues 代表堆。

类似这样的:

PriortityQueue<Integer> a = new PriorityQueue<>();
... add elements
PriortityQueue<Integer> b = new PriorityQueue<>();
... add elements
PriorityQueue<Integer> merged = new PriorityQueue<>(a.size() + b.size(), a.comparator()); // Assuming a and b have the same Comparator.
merged.addAll(a);
merged.addAll(b);

【问题讨论】:

    标签: java time-complexity big-o heap priority-queue


    【解决方案1】:

    正如您所指出的,PriorityQueue 类中的方法 add 具有 O(log(N)) 时间复杂度。如果您查看 PriorityQueue 类中方法 addAll 的具体实现,您会看到以下内容:

    public boolean addAll(Collection<? extends E> c) {
        if (c == null)
            throw new NullPointerException();
        if (c == this)
            throw new IllegalArgumentException();
        boolean modified = false;
        for (E e : c)
            if (add(e))
                modified = true;
        return modified;
    }
    

    因此,对于作为参数传递的集合中的每个元素,都会调用方法add。因此,finally 的复杂度为O(Mlog(N)),其中M 是作为参数传递的集合的元素数,N 是优先级队列的元素数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-25
      相关资源
      最近更新 更多