leeetcode回顾——Merge k Sorted Lists

题目

1
2
3
4
5
6
7
8
9
10
11
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。

示例:

输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6

题解

这其实就是归并排序从二路变为多路,原来二路的适合,可以直接比较两路得出较小的数字,而现在换成了多路,因此就可以考虑使用小顶堆这个数据结构,每次将k路的开头元素放入堆中;每取出一个最小值后,将该最小值所对应的路的开头元素放入小顶堆中,开始新一轮的选取排序

AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
import heapq
h = []
head = ListNode(-1)
tmp = head
for i in range(len(lists)):
if lists[i] != None:
heapq.heappush(h, (lists[i].val, i))
while len(h) != 0:
_, loc = heapq.heappop(h)
tmp.next = lists[loc]
tmp = tmp.next
lists[loc] = lists[loc].next
if lists[loc] != None:
heapq.heappush(h, (lists[loc].val, loc))
return head.next