合并有序链表

21. 合并两个有序链表

难度简单912收藏分享切换为英文关注反馈

将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        l3 = ListNode(-1)
        new = l3
        while l1 and l2:
            if l1.val < l2.val:
                new.next = l1
                l1 = l1.next
            else:
                new.next = l2
                l2 = l2.next
            new = new.next

        new.next = l1 if l1 is not None else l2

        return l3.next

23. 合并K个排序链表

合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。

示例:

输入:
[
  1->4->5,
  1->3->4,
  2->6
]
输出: 1->1->2->3->4->4->5->6
#两两合并,分治
class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        #两两合并,分治
        if not lists:
            return None
        
        start,end = 0,len(lists)-1
        return self.merge(lists,start,end)
            
    def merge(self,lists,start,end):
        if start == end:
            return lists[start]
        mid = start+(end-start)//2
        l1 = self.merge(lists,start,mid)
        l2 = self.merge(lists,mid+1,end)
        return self.merge2list(l1,l2)
    
    def merge2list(self,l1,l2):
        l3 = ListNode(-1)
        new = l3
        while l1 and l2:
            if l1.val < l2.val:
                new.next = l1
                l1 = l1.next
            else:
                new.next = l2
                l2 = l2.next
            new = new.next

        new.next = l1 if l1 is not None else l2

        return l3.next
posted @ 2020-03-28 19:36  鱼与鱼  阅读(160)  评论(0编辑  收藏  举报