LeetCode_Everyday:021 Merge Two Sorted Lists

LeetCode_Everyday:021 Merge Two Sorted Lists


LeetCode Everyday:堅持價值投資,做時間的朋友!!!

題目:

將兩個升序鏈表合併爲一個新的升序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。

示例:

  • 示例 1:
    輸入:1->2->4, 1->3->4
    輸出:1->1->2->3->4->4
    

代碼

方法一: 遞歸 題解

執行用時:56 ms, 在所有 Python3 提交中擊敗了18.41%的用戶
內存消耗:13.7 MB, 在所有 Python3 提交中擊敗了7.14%的用戶

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

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if l1 and l2:
            if l1.val > l2.val: l1, l2 = l2, l1
            l1.next = self.mergeTwoLists(l1.next, l2)
        return l1 or l2

"""
For Example:    input:    l1:1->2->4  l2:1->3->4
               output:    1->1->2->3->4->4
"""
l1 = ListNode(1)
l1.next = ListNode(2)
l1.next.next = ListNode(4)
l2 = ListNode(1)
l2.next = ListNode(3)
l2.next.next = ListNode(4)
                
solution = Solution()
result = solution.mergeTwoLists(l1, l2)
print('輸出爲:%d->%d->%d->%d->%d->%d' % \
      (result.val, result.next.val, result.next.next.val, result.next.next.next.val,\
      result.next.next.next.next.val, result.next.next.next.next.next.val))

方法二: 遞循環遍歷 題解

執行用時:44 ms, 在所有 Python3 提交中擊敗了79.61%的用戶
內存消耗:13.8 MB, 在所有 Python3 提交中擊敗了7.14%的用戶

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

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        dummy = ListNode(0)
        move = dummy
        while l1 and l2:
            if l1.val <= l2.val:
                move.next = l1
                l1 = l1.next
            else:
                move.next = l2
                l2 = l2.next
            move = move.next
        move.next = l1 if l1 else l2
        return dummy.next

"""
For Example:    input:    l1:1->2->4  l2:1->3->4
               output:    1->1->2->3->4->4
"""
l1 = ListNode(1)
l1.next = ListNode(2)
l1.next.next = ListNode(4)
l2 = ListNode(1)
l2.next = ListNode(3)
l2.next.next = ListNode(4)
                
solution = Solution()
result = solution.mergeTwoLists(l1, l2)
print('輸出爲:%d->%d->%d->%d->%d->%d' % \
      (result.val, result.next.val, result.next.next.val, result.next.next.next.val,\
      result.next.next.next.next.val, result.next.next.next.next.next.val))
      

參考

  1. https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/yi-kan-jiu-hui-yi-xie-jiu-fei-xiang-jie-di-gui-by-/
  2. https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/xin-shou-you-hao-xue-hui-tao-lu-bu-fan-cuo-4nian-l/

此外

  • 原創內容轉載請註明出處
  • 請到我的GitHub點點 star
  • 關注我的 CSDN博客
  • 關注我的嗶哩嗶哩
  • 關注公衆號:CV伴讀社

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章