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

相关文章:

  • 2018-10-28
  • 2021-12-20
  • 2021-09-25
  • 2021-06-18
猜你喜欢
  • 2021-09-19
  • 2021-11-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-22
  • 2022-12-23
相关资源
相似解决方案