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 ...
随机推荐
- kdbg安装使用教程(kali)
一.背景说明 所谓调试者,主要就是下断点.观察变量,不是太复杂的事情也不用太复杂的工具. 但具体到linux平台而言,gdb本来多敲几下命令也不是不可以的事,但是一个屏幕就那么大打印出一堆东西又乱又看 ...
- hosts.allow和hosts.deny支持哪些服务
一.背景简介 在linux上多用iptables来限制ssh和telnet,编缉hosts.allow和hosts.deny感觉比较麻烦比较少用. aix没有iptables且和linux有诸多不同, ...
- Mysql按日期分组(group by)查询统计的时候,没有数据补0的解决办法
转载自:http://blog.csdn.net/jie11447416/article/details/50887888 1.案例中的数据结构和数据如下 2.在没有解决的时候,是这样的 SELE ...
- JS--script标签注意细节
1)在使用<script>标签嵌入js代码时,记住不要在代码中的任何地方出现</script>字符串.例如: <script type="text/javasc ...
- numpy ndarray
>>> aarray([[1, 2], [3, 4]])>>> a.shape(2, 2)>>> barray([2, 3])>>&g ...
- html盒子水平和垂直居中
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- python-第一类对象,闭包,迭代器
# def fn(): # print("我叫fn") # fn() # print(fn) # <function fn at 0x0000000001D12E18> ...
- bootstrap学习参考网站
----https://www. evget .com /article /
- unordered_map/unordered_set & unordered_multimap/unordered_multiset非关联容器
body, table{font-family: 微软雅黑; font-size: 10pt} table{border-collapse: collapse; border: solid gray; ...
- opencv3.0+vs2013安装记录
为了能够更好的学习图像,我觉得opencv是一个必不可少的库,因此在以后的研究上使用opencv作为研究工具,与大家共同进步. 话归正题:先搭建opencv的环境. 1.下载安装包3.0 a,官网打开 ...