题目
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
合并k个有序链表
思路
可以借鉴hadoop中merge时的方法,用一个最小堆来合并
代码
Python实现
注意可以在heapq中压入一个元组,以元组的第一个元素来排序
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode[]} lists
# @return {ListNode}
def mergeKLists(self, lists):
heap=[]
for list in lists:
if list:
heap.append((list.val,list))
heapq.heapify(heap)
dummy=ListNode(0)
cur=dummy
while heap:
(val,node)=heapq.heappop(heap)
cur.next=node
cur=cur.next
if node.next:
heapq.heappush(heap,(node.next.val,node.next))
return dummy.next