https://leetcode.com/problems/merge-two-sorted-lists/
Merge Two Sorted Lists - LeetCode
Can you solve this real interview question? 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
leetcode.com
문제 요약: 정렬된 두 연결 리스트를 하나로 합쳐라(정렬 유지)
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
self.tail = self
def append(self, val):
self.tail.next = ListNode(val)
self.tail = self.tail.next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
result = None
# 예외처리
if list1 is None and list2 is None:
return result
# 초기값 계산
if list1 and (list2 is None or list1.val < list2.val):
result = ListNode(list1.val)
list1 = list1.next
else:
result = ListNode(list2.val)
list2 = list2.next
# 병합
while list1 or list2:
if list1 and (list2 is None or list1.val < list2.val):
result.append(list1.val)
list1 = list1.next
else:
result.append(list2.val)
list2 = list2.next
return result
시간복잡도 : O(n)
개선한다면...
1. result에 처음에 아무 값이나 넣어줘서 시작하고, 나중에 result.next 부터 리턴하면 굳이 초기값을 어떤걸 넣어줘야할지 결정할 계산할 필요가 없다.
2. list1이나 list2가 비어있을 경우 때문에 예외처리하느라 코드가 복잡해졌다. 둘 다 모두 있다고 생각하고 비교한 다음에, 비어있지 않은 나머지를 합쳐주면 더 깔끔해진다.
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
self.tail = self
def append(self, val):
self.tail.next = ListNode(val)
self.tail = self.tail.next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
# 임의의 초기값
result = ListNode(0)
# 병합
while list1 and list2:
if list1.val < list2.val:
result.append(list1.val)
list1 = list1.next
else:
result.append(list2.val)
list2 = list2.next
result.tail.next = list1 or list2
return result.next
'알고리즘' 카테고리의 다른 글
[프로그래머스] 올바른 괄호 (0) | 2023.04.23 |
---|---|
[leetcode/python] 206번 Reverse Linked List (0) | 2023.04.13 |
[leetcode/python] 234번 Palindrome Linked List (0) | 2023.04.13 |
[leetcode/python] 561번 Array Partition (0) | 2023.04.13 |
[leetcode/python] 42번 Trapping Rain Water (0) | 2023.04.13 |