일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- 리트코드
- Python3
- C#
- LeetCode
- 자연어처리
- GenerativeAI
- 머신러닝
- 릿코드
- Microsoft
- 파이썬알고리즘
- Azure
- nlp
- 구글퀵랩
- Blazor
- 파이썬기초100제
- 생성형AI
- 투포인터
- 코드업파이썬
- TwoPointer
- 알고리즘
- Python
- gcp
- 클라우드
- 빅데이터
- codeup
- 파이썬기초
- 파이썬
- 데이터사이언스
- GenAI
- 코드업
Archives
- Today
- Total
Tech for good
[Leetcode/Two Pointer] 19. Remove Nth Node From End of List 본문
IT/Computer Science
[Leetcode/Two Pointer] 19. Remove Nth Node From End of List
Diana Kang 2025. 2. 15. 04:47
이 문제를 한 번의 순회(One-pass)로 해결하는 방법은 두 개의 포인터(first, second)를 사용하는 것이다.
first 포인터를 먼저 n칸 이동시킨 후, second 포인터를 first와 함께 이동하면 first가 끝에 도달했을 때 second는 삭제할 노드의 직전 노드를 가리키게 된다.
✅ 알고리즘 풀이 (Two Pointer)
- 더미 노드 추가: 삭제할 노드가 head일 수도 있으므로 더미 노드를 추가.
- first 포인터 선행 이동: first를 n칸 먼저 이동.
- 두 포인터 이동: first가 리스트의 끝에 도달할 때까지 second와 함께 이동.
- 노드 삭제: second.next를 second.next.next로 변경하여 노드 삭제.
- 새로운 head 반환: dummy.next를 반환.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy = ListNode(0) # ① 더미 노드를 생성하여 head를 감싸줌 (삭제할 노드가 head일 수도 있기 때문)
dummy.next = head
first = dummy
second = dummy
# ② first 포인터를 n+1 칸 이동 (second와 n칸 차이를 만들기 위해)
for i in range(n + 1):
first = first.next
# ③ first가 리스트 끝까지 가도록 first, second 함께 이동
while first is not None:
first = first.next
second = second.next
# ④ second.next가 삭제할 노드이므로 건너뛰도록 변경
second.next = second.next.next
# ⑤ 새로운 head 반환
return dummy.next
⏳ 시간 복잡도 분석
- O(N): 리스트를 한 번만 순회하므로 O(N)의 시간 복잡도를 가짐.
- O(1): 추가적인 공간을 거의 사용하지 않음.
https://leetcode.com/problems/remove-nth-node-from-end-of-list/
'IT > Computer Science' 카테고리의 다른 글
[Leetcode/Two Pointer] 75. Sort Colors (0) | 2025.02.16 |
---|---|
[Leetcode/Two Pointer] 283. Move Zeroes (0) | 2025.02.16 |
[Leetcode/Hash Set] 653. Two Sum IV - Input is a BST (0) | 2025.02.15 |
[Leetcode/Two Pointer] 653. Two Sum IV - Input is a BST (0) | 2025.02.15 |
[Dart/Flutter] Flutter 앱 개발을 위한 Dart 배우기 - 2. Data Types (0) | 2023.03.04 |