Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6
This is a hard problem??? Oh, it is! Actually, it's a very good problem, quite like merge sort. But the background is the list, LOL.
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if len(lists)==0:
return None
if len(lists)==1:
return lists[0]
l1=self.mergeKLists(lists[:len(lists)/2])
l2=self.mergeKLists(lists[len(lists)/2:])
return self.mergeTwoList(l1,l2)
def mergeTwoList(self,l1,l2):
dummy=ListNode(0)
cur=dummy
while l1 and l2:
if l1.val <l2.val:
cur.next=l1
l1=l1.next
else:
cur.next=l2
l2=l2.next
cur=cur.next
if l1:
cur.next=l1
if l2:
cur.next=l2
return dummy.next
本文介绍了一种高效的方法来合并多个已排序的链表成为一个单一的排序链表。通过递归地将链表分成两半并分别进行合并,最终实现了两两合并的功能。这种方法类似于归并排序,但背景是在链表上实现。
761

被折叠的 条评论
为什么被折叠?



