Leetcode 23. Merge K sorted lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
思路:参考:http://www.cnblogs.com/zuoyuan/p/3772372.html
一开始的思路类似merge two sorted lists。比较所有list head.val,那个最小就把dummy指向那个ListNode,然后把相应的那个list的head往后挪一格。但是由于K不知道是多少,比较难操作。根据提示使用heap。把所有的head都push进一个heap。pop出值最小的那个,把dummy指向那个元素。然后将对应的那一个list中的下一个元素(新的head node)pushi进heap,重复上述操作。
注意和heap相关的几个操作。heapq.heapify, heapq.pop(heap), heapq.push(heap, xxxx)
1 class Solution(object): 2 def mergeKLists(self, lists): 3 """ 4 :type lists: List[ListNode] 5 :rtype: ListNode 6 """ 7 heap = [] 8 for node in lists: 9 if node: 10 heap.append((node.val, node)) 11 heapq.heapify(heap) 12 dummy = ListNode(0) 13 curr = dummy 14 while heap: 15 pop = heapq.heappop(heap) 16 curr.next = ListNode(pop[0]) 17 curr = curr.next 18 if pop[1].next: 19 heapq.heappush(heap, (pop[1].next.val, pop[1].next)) 20 return dummy.next 21 22
用K的元素构造heap的complexity是KlogK, 然后将一个元素push进heap的complexity是logK。所以总复杂度是KlogK + nlogK