【问题标题】:Complexity of inserting into priority queue插入优先级队列的复杂性
【发布时间】:2016-07-07 19:50:24
【问题描述】:

考虑以下代码,该代码从优先级队列中弹出前 2 个元素,将它们相加并将总和插入回优先级队列。

while (pq.size() > 1)
{
    // Extract shortest two ropes from pq
    int first = pq.top();
    pq.pop();
    int second = pq.top();
    pq.pop();

    // Connect the ropes: update result and
    // insert the new rope to pq
    res += first + second;
    pq.push(first + second);
}

众所周知,将n个元素插入优先级队列是O(nlogn)操作。但是可以说优先级队列是作为数组实现的。 它不会变成 O(N*N) 操作。 或者上面 n 个元素的代码的复杂度是多少。

【问题讨论】:

    标签: queue big-o complexity-theory priority-queue


    【解决方案1】:

    实现良好的优先级队列将在每次插入 O (log n) 摊销步骤中插入元素。一个实现良好的优先级队列很可能使用数组,数组元素根据堆排序算法排列。

    【讨论】:

    • 但是如果它被实现为一个数组,我们还需要将元素向右移动以便为插入腾出空间。那么在这种情况下,N 个元素不会导致 O(N*N) 吗?
    • @AshishChopra,不,优先级队列是使用堆实现的,而堆又是使用数组实现的。将元素插入堆只是一系列交换。看看heapsort
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    相关资源
    最近更新 更多