Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
分析1:
利用上一道题(合并两个有序链表)代码,进行两两合并,最后得到一个链表。代码如下,然而一直超时。
超时的代码:
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if len(lists) == 0:
return None
else:
l3 = None
for l in lists:
l3 = reduce(self.mergetTwoLists, lists)
return l3.next
分析2:
利用最小堆的特性,将每个链表放入最小堆中,每次从堆中取出一个ListNode p,同时往里面插入p的后序ListNode(如果存在的话)。我按算法导论的堆的伪码,用Python实现了一个最小堆完成了这道题。如果你看下面这段代码的话,你可以使用Python的heapq模块中的函数替换我写的渣渣代码,同时可以去看看heapq中的实现。
代码:
def Parent(i):
return i/2
def Left(i):
return 2*i
def Right(i):
return 2*i + 1
def minHeapify(h, i):
l = Left(i)
r = Right(i)
if l < len(h) and h[l] < h[i]:
minlst = l
else:
minlst = i
if r < len(h) and h[r] < h[minlst]:
minlst = r
if minlst != i:
h[i], h[minlst] = h[minlst], h[i]
minHeapify(h, minlst)
def buildMinHeap(h):
half_len = len(h) / 2
while half_len >= 0:
minHeapify(h, half_len)
half_len -= 1
return h
def upAdjust(h, i):
while i >= 0 and h[Parent(i)] > h[i]:
h[Parent(i)], h[i] = h[i], h[Parent(i)]
i = Parent(i)
def heapPush(h, item):
h.append(item)
upAdjust(h, len(h) - 1)
def heapPop(h):
if len(h) == 0:
return None
min_val = h[0]
h[0] = h[len(h) - 1]
del h[len(h) - 1]
minHeapify(h, 0)
return min_val
# 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
"""
# from heapq import heappush, heappop, heapify
h = [(l.val, l) for l in lists if l]
buildMinHeap(h)
head = rl = ListNode(0)
while h:
rl.next = heapPop(h)[1]
print rl.next.val
rl = rl.next
if rl.next:
heapPush(h, (rl.next.val, rl.next))
return head.next