LeetCode 솔루션 분류
[Easy - wk2 - Q1] 21. Merge Two Sorted Lists
본문
You are given the heads of two sorted linked lists list1
and list2
.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Example 1:
Input: list1 = [1,2,4], list2 = [1,3,4] Output: [1,1,2,3,4,4]
Example 2:
Input: list1 = [], list2 = [] Output: []
Example 3:
Input: list1 = [], list2 = [0] Output: [0]
Constraints:
- The number of nodes in both lists is in the range
[0, 50]
. -100 <= Node.val <= 100
- Both
list1
andlist2
are sorted in non-decreasing order.
태그
#leetcode, #문제풀이, #easy, #amazon, #microsoft, #facebook, #adobe, #oracle, #uber, #google, #bloomerg, #shopee, #accenture, #linked list, #recursion
관련자료
-
링크
댓글 2
yuun님의 댓글
- 익명
- 작성일
class Solution:
def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(0)
l3 = dummy
while l1 and l2:
if l1.val < l2.val:
l3.next = l1
l1 = l1.next
else:
l3.next = l2
l2 = l2.next
l3 = l3.next
if l1:
l3.next = l1
if l2:
l3.next = l2
return dummy.next
Jack님의 댓글
- 익명
- 작성일
Python
Runtime: 57 ms, faster than 36.18% of Python3 online submissions for Merge Two Sorted Lists.
Memory Usage: 13.8 MB, less than 80.22% of Python3 online submissions for Merge Two Sorted Lists.
Runtime: 57 ms, faster than 36.18% of Python3 online submissions for Merge Two Sorted Lists.
Memory Usage: 13.8 MB, less than 80.22% of Python3 online submissions for Merge Two Sorted Lists.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if ( not list1) or (list2 and list1.val > list2.val):
list1, list2 = list2, list1
if list1:
list1.next = self.mergeTwoLists(list1.next, list2)
return list1