首页 > 其他 > 详细

合并两个有序链表

时间:2020-06-25 09:44:47      阅读:60      评论:0      收藏:0      [点我收藏+]
  • 方法1:迭代

    m、n为两个有序链表的长度

    时间复杂度:O(m+n)

    空间复杂度:O(1)

    class ListNode:
        def __init__(self, val=0, next=None):
            self.val = val
            self.next = next
    class Solution:
        def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
            prehead = ListNode(-1)
            pre = prehead
            while l1 and l2:
                if l1.val <= l2.val:
                    pre.next = l1
                    l1 = l1.next
                else:
                    pre.next = l2
                    l2 = l2.next
                pre = pre.next
            pre.next = l1 if l1 is not None else l2
            return prehead.next
    
  • 方法2:递归

    m、n为两个有序链表的长度

    时间复杂度:O(m+n)

    空间复杂度:O(m+n)

    class ListNode:
        def __init__(self,val=0,next=None):
            self.val = val
            self.next = next
    class Solution:
        def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
            if not l1:
                return l2
            if not l2:
                return l1
            if l1.val <= l2.val:
                l1.next = self.mergeTwoLists(l1.next,l2)
                return l1
            else:
                l2.next = self.mergeTwoLists(l1,l2.next)
                return l2
        
    

合并两个有序链表

原文:https://www.cnblogs.com/gugu-da/p/13190944.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!