Skip to content

Commit eede72a

Browse files
committed
solve: remove-nth-node-from-end-of-list
1 parent ffe1385 commit eede72a

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# Intuition
2+
n번 μ§Έλ₯Ό μ•ŒκΈ° μœ„ν•΄ 정보(λͺ‡ λ²ˆμ§Έμ— μ–΄λ–€ μš”μ†Œκ°€ μžˆλŠ”μ§€)λ₯Ό μ•Œμ•„μ•Ό ν•œλ‹€.
3+
# Approach
4+
1. 배열에 λ§ν¬λ“œ 리슀트 정보λ₯Ό λͺ¨λ‘ λ„£λŠ”λ‹€.
5+
2. 맨 μ•ž μš”μ†Œλ₯Ό μ œκ±°ν•΄μ•Όν•˜λŠ” 경우 (`len(nodes) == n`) ν—€λ“œμ˜ λ‹€μŒμ„ λ°˜ν™˜ν•œλ‹€.
6+
3. λ’€μ—μ„œ `n`번째 μš”μ†Œ(`len(nodes)-n`)의 μ•žκ³Ό λ’€λ₯Ό 이어뢙여 `n`번째 μš”μ†Œλ₯Ό μ œκ±°ν•œλ‹€.
7+
# Complexity
8+
- Time complexity: $O(n)$
9+
- λ§ν¬λ“œ 리슀트의 길이 `n`에 λŒ€ν•˜μ—¬, 이λ₯Ό μˆœνšŒν•˜λŠ” λΉ„μš©μ΄ λ°œμƒν•œλ‹€.
10+
- Space complexity: $O(n)$
11+
- λ§ν¬λ“œ 리슀트의 길이 `n`에 λŒ€ν•˜μ—¬, λ°°μ—΄μ˜ 크기 `n`이 λ°œμƒν•œλ‹€.
12+
13+
# Code
14+
## Array
15+
```go
16+
func removeNthFromEnd(head *ListNode, n int) *ListNode {
17+
nodes := make([]*ListNode, 0, 100)
18+
19+
for curr := head; curr != nil; curr = curr.Next {
20+
nodes = append(nodes, curr)
21+
}
22+
23+
if len(nodes) == n {
24+
return head.Next
25+
}
26+
27+
nodes[len(nodes)-n-1].Next = nodes[len(nodes)-n].Next
28+
return head
29+
}
30+
31+
```
32+
# Intuition
33+
λ°°μ—΄μ˜ λͺ¨λ“  μ›μ†Œλ₯Ό μ €μž₯ν•  ν•„μš”λŠ” μ—†μ–΄ λ³΄μ˜€λ‹€. 곡간 λ³΅μž‘λ„λ₯Ό 쀄일 방법을 μ•Œμ•„λ³΄μ•˜λ‹€.
34+
# Approach
35+
λͺ¨λ“  μ›μ†Œκ°€ μ•„λ‹ˆλΌ, `n`번째의 이전(`prev`), 이후 (`next`)λ§Œμ„ μ €μž₯ν•˜κ²Œ ν•˜μ˜€λ‹€.
36+
# Complexity
37+
- Time complexity: $O(n)$
38+
- λ§ν¬λ“œ 리슀트의 길이 `n`에 λŒ€ν•˜μ—¬, 이λ₯Ό μˆœνšŒν•˜λŠ” λΉ„μš©μ΄ λ°œμƒν•œλ‹€.
39+
- Space complexity: $O(1)$
40+
- 2개의 μš”μ†Œλ§Œ μœ μ§€ν•˜λ―€λ‘œ, `O(1)`이닀.
41+
42+
# Code
43+
## Two Pointer
44+
```go
45+
func removeNthFromEnd(head *ListNode, n int) *ListNode {
46+
len := 0
47+
for curr := head; curr != nil; curr = curr.Next {
48+
len++
49+
}
50+
51+
if len == n {
52+
return head.Next
53+
}
54+
55+
var prev, curr, next *ListNode
56+
curr = head
57+
next = head.Next
58+
for i := 0; i+n < len; i++ {
59+
prev = curr
60+
curr = next
61+
next = next.Next
62+
}
63+
64+
prev.Next = next
65+
return head
66+
}
67+
68+
```

0 commit comments

Comments
Β (0)