python 中的堆 (heapq 模块)应用:Merge K Sorted Lists
堆是计算机科学中一类特殊的数据结构的统称。堆通常是一个可以被看做一棵树的数组对象。在队列中,调度程序反复提取队列中第一个作业并运行,因为实际情况中某些时间较短的任务将等待很长时间才能结束,或者某些不短小,但具有重要性的作业,同样应当具有优先权。堆即为解决此类问题设计的一种数据结构。
1 定义
n个元素序列{k1,k2...ki...kn},当且仅当满足下列关系时称之为堆:
(ki <= k2i, ki <= k2i+1)或者(ki >= k2i, ki >= k2i+1), (i = 1,2,3,4...n/2)
2 性质
堆的实现通过构造二叉堆(binary heap),实为二叉树的一种;由于其应用的普遍性,当不加限定时,均指该数据结构的这种实现。这种数据结构具有以下性质。
- 任意节点小于(或大于)它的所有后裔,最小元(或最大元)在堆的根上(堆序性)。
- 堆总是一棵完全树。即除了最底层,其他层的节点都被元素填满,且最底层尽可能地从左到右填入。
将根节点最大的堆叫做最大堆或大根堆,根节点最小的堆叫做最小堆或小根堆。常见的堆有二叉堆、斐波那契堆等。
3 应用
3.1 heapq 模块中的重要函数
>>> import heapq
>>> heapq.__all__
['heappush', 'heappop', 'heapify', 'heapreplace', 'merge', 'nlargest', 'nsmallest', 'heappushpop']
heappush(heap, x) 将 x 入堆
heappop(heap) 将堆属性中的最小元素弹出
heapify(heap) 将 heap 属性强制应用到任意一个列表
heapreplace(heap, x) 将堆中的最小的元素弹出,同时将 x 入堆
merge() 多个堆合并
nlargest(n, iter) 返回 iter 中的第 n 大的元素
nsmallest(n, iter) 返回 iter 中的第 n 小的元素
3.2 创建堆结构
list1 = [3,2,8,1,4,5]
heapq.heapify(list1)
list2 = []
heapq.heappush(list2, 3)
heapq.heappush(list2, 2)
heapq.heappush(list2, 8)
heapq.heappush(list2, 1)
heapq.heappush(list2, 4)
heapq.heappush(list2, 5)
list1
Out[110]: [1, 2, 5, 3, 4, 8]
list2
Out[108]: [1, 2, 5, 3, 4, 8]
以上两种方法创建的堆是一样的,元素推入堆后会自动按照二叉树的规范重新排序
3.3 Merge K sorted Lists
用堆的思想合并k个排序链表,并且返回合并后的排序链表。
思路1:
将所有链表的节点 push 到堆中,每次把最小的 pop 出来。代码如下:
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
import heapq
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
heap = []
for node in lists:
while node:
heapq.heappush(heap, node.val)
node = node.next
temp = ListNode(-1)
head = temp
while heap:
smallestNode_val = heapq.heappop(heap)
temp.next = ListNode(smallestNode_val)
temp = temp.next
return head.next
思路2:
不用堆用列表也能实现,代码如下:
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
l = []
for node in lists:
while node:
l.append(node.val)
node = node.next
l.sort()
temp = ListNode(-1)
head = temp
for i in l:
temp.next = ListNode(i)
temp = temp.next
return head.next
参考资料:
python 中的堆 (heapq 模块)应用:Merge K Sorted Lists的更多相关文章
- [Leetcode][Python]23: Merge k Sorted Lists
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 23: Merge k Sorted Listshttps://oj.leet ...
- 蜗牛慢慢爬 LeetCode 23. Merge k Sorted Lists [Difficulty: Hard]
题目 Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity ...
- Merge k Sorted Lists
1. Merge Two Sorted Lists 我们先来看这个 问题: Merge two sorted linked lists and return it as a new list. The ...
- LeetCode: Merge k Sorted Lists 解题报告
Merge k Sorted Lists Merge k sorted linked lists and return it as one sorted list. Analyze and descr ...
- Leetcode 23.Merge Two Sorted Lists Merge K Sorted Lists
Merge Two Sorted Lists Merge two sorted linked lists and return it as a new list. The new list shoul ...
- Merge k Sorted Lists——分治与堆排序(需要好好看)
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 1 ...
- 71. Merge k Sorted Lists
Merge k Sorted Lists Merge k sorted linked lists and return it as one sorted list. Analyze and descr ...
- 【leetcode】Merge k Sorted Lists
Merge k Sorted Lists Merge k sorted linked lists and return it as one sorted list. Analyze and descr ...
- 【LeetCode练习题】Merge k Sorted Lists
Merge k Sorted Lists Merge k sorted linked lists and return it as one sorted list. Analyze and descr ...
随机推荐
- 485. Max Consecutive Ones最大连续1的个数
网址:https://leetcode.com/problems/max-consecutive-ones/ 很简单的一题 class Solution { public: int findMaxCo ...
- python之命令行参数解析模块argparse
"""argparse模块使得写用户友好性命令行接口很容易,程序定义所需要的参数,argparse会从ays.argv中提取出这些参数.argparse模块也能自动的产生 ...
- Oracle12c CDB架构图
- rexec/rlogin/rsh介绍
服务 是否需要密码 是否明文 功能 端口 rexec 是 是 远程执行命令 512 rlogin 是 是 远程登录得到shell 513 rsh 是 是 可远程执行命令,也可远程登录得到shell 5 ...
- RWCString 定义 memeroy leak
代码截取片段: testDefs.hh class testDefs { public: static const RWCString testStr; }; testDefs.cc const RW ...
- js--事件冒泡-捕获
什么是事件流: 事件流描述的是从页面中接受事件的顺序,但有意思的是,微软(IE)和网景(Netscape)开发团队居然提出了两个截然相反的事件流概念, IE的事件流是事件冒泡流(event bubbl ...
- windows下的pycharm配置 linux环境
由于最近学习python的需要,为了方便程序的调试,尝试在Windows下的Pycharm远程连接到虚拟机中Centos下的python环境.(这里我采用的是ssh的远程连接)1.准备工作: 固定ce ...
- TiDB 深度实践之旅--真实“踩坑”经历
美团点评 TiDB 深度实践之旅(9000 字长文 / 真实“踩坑”经历) 4 PingCAP · 154 天前 · 3956 次点击 这是一个创建于 154 天前的主题,其中的信息可能已经有所发 ...
- 《Python》线程之锁、信号量、事件、条件、定时器、队列
一.锁 线程为什么要有锁: += .-= 赋值操作数据不安全(要经过取值.计算.放回值,3部操作) pop .append 都是数据安全的(只有添加和删除,一次操作) 队列也是数据安全的 1.同步锁 ...
- 《Python》 计算机基础
一.计算机基础: cpu:中央处理器,相当于人的大脑,运算中心,控制中心. 内存:暂时存储数据,与CPU交互. 优点:内存读取速度快. 缺点:容量小,造价高,断电即消失. 硬盘:长期存储数据. 优点: ...