python 小顶堆
来源:互联网 发布:ipad软件开发 编辑:程序博客网 时间:2024/06/03 21:31
转自http://blog.csdn.net/tanghaiyu777/article/details/55271004
参考链接
https://www.coder4.com/archives/3844
求一个数列前K大数的问题经常会遇到,在程序中一般用小顶堆可以解决,下面的代码是使用python的heapq实现的小顶堆示例代码:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
python的heapq在实现的时候,没有像STL或者Java可以传入比较函数,具体的原因可以参考参考文档给出的链接。
因此有些人想出了比较trick的思路。一句话概括如下:
push(e)改为push(-e),pop(e)为-pop(e),也就是说存入和取出的数都是相反数,其他逻辑和TopK相同。(点赞)
实现用户自定义的比较函数,允许elem是一个tuple,按照tuple的第一个元素进行比较,所以可以把tuple的第一个元素作为我们的比较的key。
英文原话:
The heapq documentation suggests that heap elements could be tuples in which the first element is the priority and defines the sort order.
阅读全文
0 0
- python 小顶堆
- Python
- Python
- Python
- python
- Python
- PYTHON
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- Python
- python
- 编辑距离
- curl
- java判断字符串是否为空的方法总结
- IO流操作.MyIOHelper.可以当做Utils直接使用
- 蓝桥杯 算法训练 动态数组使用
- python 小顶堆
- 显著性水平 P值 概念解释
- 深度学习11
- 关于scrapy采集网易云音乐歌手遇到的问题
- Capstone日志2017-12-11
- spoon各个控件的说明
- Win8.1下安装ubuntu16.04双系统
- 51Nod 1428 活动安排问题 贪心+优先队列
- .NET程序四舍五入