题目
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
题目要求
将k个有序的列表组合成一个大的有序列表,并分析实现的复杂度
解题思路
此题参考kitt blog,使用小根堆结构进行实现。
先将所有列表按照第一个元素的大小放入小根堆中,然后每次取回最小的元素的列表,将该列表下一个元素放入小根堆中。直到小根堆为空。这样就得到了排好序的一个列表。小根堆构建的复杂度为
O(NlogN)
,每次取最小值的复杂度为
O(logN)
,向小根堆添加元素的复杂度为
O(logN)
。所有总的实现复杂度为
O(NlogN)
。
在本次实现中直接使用了Python提供的小根堆的结构。
heapq使用说明
a为普通列表
- heapq.heapify(a) 调整a,使得其满足最小堆
- heapq.heappop(a) 从最小堆中弹出最小的元素
- heapq.heappush(a,b) 向最小堆中压入新的元素
代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
heap = []
for l in lists:
if l != None:
heap.append((l.val,l))
heapq.heapify(heap)
dummy = ListNode(0)
cur = dummy
while heap:
_,h = heapq.heappop(heap)
cur.next = h
cur = cur.next
if h.next:
heapq.heappush(heap,(h.next.val,h.next))
return dummy.next