【问题标题】:Dequeue in a priority queue在优先级队列中出列
【发布时间】:2016-01-28 11:13:42
【问题描述】:

我已经用数组(学校作业)实现了一个优先级队列,如下所示:

int dequeue(int a[], int n){

    int i, numberToDequeue;
    numberToDequeue = a[0];

    for(i = 0; i < n; i++){
        a[i] = a[i+1];
    }
    return numberToDequeue;
}

优先级队列中的出队需要 O(1) 时间。

但是,在我的代码中,需要 O(1) 时间才能出列和

O(n) 时间将所有元素向前移动 1 个索引。

我想知道是否有任何更好的解决方案具有 O(1) 的时间复杂度。

所有形式的回复将不胜感激。

【问题讨论】:

  • 队列实际上并不需要放入连续内存中...
  • 查找 C++ 循环缓冲区
  • 好吧,我发现我实际上可以按升序对我的数字进行排序,所以我可以在每次出队后减少我的 arraySize,而不是让 for 循环将每个元素移到前面 1 个索引。

标签: c++ arrays sorting priority-queue


【解决方案1】:
int dequeue(int a[], int n){ //provided that the numbers are in ascending order

    int numberToDequeue;
    numberToDequeue = a[n - 1];
    n--;
    return numberToDequeue;
}

【讨论】:

  • 欢迎来到 Stack Overflow!虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
猜你喜欢
  • 1970-01-01
  • 2011-12-20
  • 1970-01-01
  • 1970-01-01
  • 2011-03-20
  • 1970-01-01
  • 1970-01-01
  • 2013-02-13
  • 1970-01-01
相关资源
最近更新 更多