如何使用两个队列实现优先级队列

 平凡天使007 发布于 2023-02-07 11:10

在面试问题中,我被要求使用队列实现优先级队列,

在采访之后我用Google搜索并发现它可以使用两个队列实现,但我没有找到如何...

请任何人解释我.

提前致谢.

1 个回答
  • 使用优先级队列的主要优点是我们可以在恒定时间获得最小值/最大值.所以这是应该满足的第一个标准.我们只考虑关键价值观.我们可以使用两个队列创建一个prioity队列,如果输入元素大于q1的顶部,则将它们命名为q1和q2,然后将其附加到q1 else

    如果输入小于q1的顶部,则重复

    从q1中删除元素并插入到q2,直到top大于该元素

    现在添加元素

    现在将剩余的元素插入q2

    so like input is 2 4 1 5 3
    pass 1)
    q1-> 2 
    q2->  
    pass 2)
    q1-> 2 4
    q2->
    pass 3)
    q1-> 
    q2->1 2 4 // since 1 is less than top of q1 add it to q2 and then pop all the elements to q2
    pass 4)
    q1-> 
    q2-> 1 2 4 5 //add it to q2 since it is larger than all the elements
    pass 5)
    q1-> 1 2 3 4 5//pop the elements smaller than q3 and then add the element and append the        remaining
    
    q2->
    

    2023-02-07 11:13 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有