题目描述
合并k个排序链表,并且返回合并后的排序链表。尝试分析和描述其复杂度。
样例
给出3个排序链表[2->4->null,null,-1->null],返回 -1->2->4->null
思路
两两合并,如果是奇数,余出来的直接加在最后。
代码
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param lists: a list of ListNode
@return: The head of one sorted list.
"""
def mergeKLists(self, lists):
# write your code here
if lists is None or len(lists) == 0:
return None
while len(lists) > 1:
tmp = []
for i in range(0, len(lists) - 1, 2):
p = self.mergeTwoList(lists[i], lists[i + 1])
tmp.append(p)
if len(lists) % 2 == 1:
tmp.append(lists[-1])
lists = tmp
return lists[0]
def mergeTwoList(self, l1, l2):
if l1 is None:
return l2
if l2 is None:
return l1
res = ListNode(0)
r = res
while l1 is not None and l2 is not None:
if l1.val <= l2.val:
r.next = l1
l1 = l1.next
else:
r.next = l2
l2 = l2.next
r = r.next
if l1 is not None:
r.next = l1
if l2 is not None:
r.next = l2
return res.next
复杂度分析
时间复杂度 O(nklogk) ,空间复杂度 O(1) 。