Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 인프콘 2024
- jwt
- 코딩테스트 준비
- 항해99
- infcon 2024
- spring batch 5.0
- 디자인 패턴
- DesignPattern
- 디자인패턴
- 1주일회고
- Spring multimodule
- 개발자부트캠프추천
- jwttoken
- 프로그래머스
- 취업리부트코스
- JavaScript
- @FeignClient
- KPT회고
- 99클럽
- 빈 충돌
- 커스텀 헤더
- 단기개발자코스
- 파이썬
- 전략패턴 #StrategyPattern #디자인패턴
- TiL
- 개발자 취업
- 프로그래머스 이중우선순위큐
- 구글 OAuth login
- Python
- 빈 조회 2개 이상
Archives
- Today
- Total
m1ndy5's coding blog
LeetCode 21. Merge Two Sorted Lists with Python 본문
https://leetcode.com/problems/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]:
# 새로운 리스트노드 생성
curr = dummy = ListNode()
while list1 and list2:
# 더 작은 값을 현재 뒤에다 붙임
if list1.val < list2.val:
curr.next = list1
list1 = list1.next
else:
curr.next = list2
list2 = list2.next
curr = curr.next
# 남아있는 리스트를 그 뒤에 붙임
if list1 or list2:
curr.next = list1 if list1 else list2
# 처음에 의미없는 헤드 뒤부터
return dummy.next
list1과 list2를 비교하면서 새로운 연결리스트에 값을 붙이는 방법이다.
이 때 둘중에 하나가 None이 되면 남아있는 리스트를 고대로 뒤에 붙이면 된다.
dummy의 헤드는 의미없는 노드이므로 뒤를 출력한다.
책 코드
def mergeTwoLists(self, l1: ListNode, l2: ListNode):
# l1 기준으로 정렬
# l1이 비었거나 l1이 더 값이 크면 l2를 l1으로 바꿈
if (not l1) or (l2 and l1.val > l2.val):
l1, l2 = l2, l1
# l1이 None일때까지 계속 재귀
if l1:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
굉장히 간단하게 재귀로 풀었다.
따로 새로운 연결리스트를 만들지 않고 l1에 계속 붙이는게 신기했던 코드였다.
'알고리즘 with python > 알고리즘 스터디' 카테고리의 다른 글
LeetCode 17. Letter Combinations of a Phone Number with Python (1) | 2024.01.10 |
---|---|
LeetCode 328. Odd Even Linked List with Python (0) | 2024.01.06 |
LeetCode 206.Reverse Linked List with Python (0) | 2024.01.06 |
LeetCode 215. Kth Largest Element in an Array with Python (0) | 2024.01.05 |
LeetCode 1337. The K Weakest Rows in a Matrix with Python (1) | 2024.01.05 |