[リスト] Leetcodeマージ2つの命じたリスト(21)

タイトル

2は、新たなソートされたリストとリターンにリストを命じました。新しいリストは、二つのリストで構成与えられたモザイク内のすべてのノードです。

例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

输入:1->2->4, 5
输出:1->2->4->5

問題の解決策

三つの方法:

  • テール補間は、元のリストを変更します。O(N)の時間計算量は、空間的複雑度はO(1)
  • 元のリストは変更されず、新しいスペースを開くために、他のです。O(N + M)、Oの空間的複雑さ(N + M)の時間計算量
  • 再帰的には、私は理解していませんでした。

コードにより、次のとおりです。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # 方法一:
    # 尾插法,更改原始链表。时间复杂度O(n),空间复杂度O(1)
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        thead = ListNode(-1)  # 开辟一个表头结点,用于返回时候使用
        t = thead
        while l1 and l2:
            if l1.val<=l2.val:
                t.next = l1
                t = l1
                
                l1 = l1.next
            else:
                t.next = l2
                t = l2

                l2 = l2.next
        # 以下是把没走完的链表添加到尾部
        if l1:
            t.next = l1
        if l2:
            t.next = l2
        return thead.next


    # # 方法二:
    # # 原链表不变,另开辟新空间。时间复杂度O(n+m),空间复杂度O(n+m)
    # def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
    #     head = ListNode(0)
    #     temp = head
    #     c2 = l2
    #     while l1 and c2:
    #         if l1.val <= c2.val:
    #             t = ListNode(l1.val)
    #             temp.next = t
    #             temp = t
                
    #             l1 = l1.next            
    #         else:
    #             t = ListNode(c2.val)
    #             temp.next = t
    #             temp = t

    #             c2 = c2.next
    #     while l1:
    #         temp.next = l1
    #         temp = l1
    #         l1 = l1.next
    #     while c2:
    #         temp.next = c2
    #         temp = c2
    #         c2 = c2.next
    #     return head.next


    # # 方法三:递归,这个答案是抄的,没懂。。。
    # 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

おすすめ

転載: www.cnblogs.com/ldy-miss/p/11935619.html