一:题意
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
python实现
from Queue import PriorityQueue
class Solution(object):
def mergeKLists(self, lists):
# ---------暴力法----------------------------------------------
# 时间:O(N) + O(NlogN)
# 空间:O(N)
# self.nodes = []
# head = point = ListNode(0)
# for l in lists:
# while l:
# self.nodes.append(l.val)
# l = l.next
# for x in sorted(self.nodes): # 排序真好
# point.next = ListNode(x)
# point = point.next
# return head.next
# -----------归并排序(把所有链表先合成一个,Leetcode 148. Sort List)-------
# 时间:O(N) + O(NlogN) 还是不是最优的
# 空间:O(1)
# ---------优先队列或者最小堆------------------------------------------------
# 时间:O(N) + O(NlogK) 不是最优的情况啊,空间还可以优化
# 空间:O(N) + O(K)
# head = p = ListNode(-1)
# q = PriorityQueue()
# for L in lists: # 头结点
# if L: q.put((L.val, L)) # (k个链表头结点的值,头结点)
# while not q.empty():
# val, node = q.get() # 取出并弹出来
# p.next = ListNode(val)
# p = p.next
# node = node.next
# if node: q.put((node.val, node))
# return head.next
# ----------Merge with Divide And Conquer(升级的归并排序)-----------------------------
# 时间:O(NlogK) 还是最优的情况啊
# 空间:O(1)
def merge(head1, head2): # 合并两个链表,有空链表时也可以!
newHead = ListNode(-1)
p = newHead
while head1 and head2:
if head1.val <= head2.val:
p.next = head1
p = p.next
head1 = head1.next
else:
p.next = head2
p = p.next
head2 = head2.next
if head1: p.next = head1
if head2: p.next = head2
return newHead.next
n = len(lists)
if n < 1: return None
interval = 1
while interval < n:
for i in range(0, n-interval, interval*2): # 先两两合并
lists[i] = merge(lists[i], lists[i+interval])
interval *= 2 # 再四四合并,再八八合并
return lists[0]