21. Merge Two Sorted Lists (Easy)

Description:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4


Solutions:

My solution:

# 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 == None:
            return l2
        elif l2 == None:
            return l1
        
        if l1.val < l2.val:
            start = l1 
            start.next = self.mergeTwoLists(l1.next,l2)
        else:
            start = l2
            start.next = self.mergeTwoLists(l1,l2.next)
            
        return start

Performance:

  • Runtime: 44 ms, faster than 80.82% of Python3 online submissions for Merge Two Sorted Lists.
  • Memory Usage: 13.4 MB, less than 5.33% of Python3 online submissions for Merge Two Sorted Lists.

Solution2: top solution from leetcode

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:

        if l1 == None:
            return l2
        elif l2 == None:
            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

Performance:

和上面其实差不多,偶然能到99.9%,平均来说稍快。原因可能是省略了创建ListNode的过程。想了想确实没必要新建一个ListNode。

你可能感兴趣的:(21. Merge Two Sorted Lists (Easy))