[목록] Leetcode 병합 개의 주문 목록 (21)

이름

두 사람은 새로운 정렬 된 목록 및 반환에 목록을 명령했다. 새로운 목록은 두 목록으로 구성 주어진 모자이크의 모든 노드입니다.

예 :

输入: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