Skip to content

Commit ffe1385

Browse files
committed
solve: reorder-list
1 parent 0ce8e58 commit ffe1385

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

โ€Žreorder-list/invidam.go.mdโ€Ž

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# Intuition
2+
<!-- Describe your first thoughts on how to solve this problem. -->
3+
์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•œ ํ’€์ด๋ฅผ ์ƒ๊ฐํ•˜์˜€์œผ๋‚˜, ๋งจ ๋’ค์— ์žˆ๋Š” ์š”์†Œ๊ฐ€ 2๋ฒˆ์งธ ๊นŒ์ง€ ์žฅ๊ฑฐ๋ฆฌ ์ด๋™ํ•ด์•ผ ํ•˜๋ฏ€๋กœ ๋งจ ๋’ค๋ฅผ `O(1)`์— ์ ‘๊ทผํ•˜๊ธฐ ์œ„ํ•œ ๋ฐฉ๋ฒ•(๋ฐฐ์—ด์„ ๋– ์˜ฌ๋ฆผ)์ด ํ•„์š”ํ•  ๊ฒƒ์ด๋‹ค.
4+
<!-- Describe your approach to solving the problem. -->
5+
1. Deque์•ˆ์— ๋ชจ๋“  ๋…ธ๋“œ๋“ค์„ ์‚ฝ์ž…ํ•œ๋‹ค.
6+
- ์ฝ”๋“œ์—์„œ๋Š” ๋ฐฐ์—ด(`nodes`)์™€ ๋‘ ์ธ๋ฑ์Šค(`i`, `j`)๊ฐ€ `Deque`์˜ ์—ญํ• ์„ ๋Œ€์‹ ํ•œ๋‹ค.
7+
2. ๋งจ ์•ž, ๋งจ ๋’ค์—์„œ ํ•˜๋‚˜์”ฉ์„ ๋บ€๋‹ค. (`f`, `b`)
8+
3. ๋งจ ์•ž ์š”์†Œ ๋’ค์— ๋งจ ๋’ค ์š”์†Œ๋ฅผ ๋„ฃ๋Š”๋‹ค. (`f` --> `b` -- (๊ธฐ์กด) `f.Next`)
9+
3. reorder์ดํ›„ ๋งจ ๋งˆ์ง€๋ง‰ ์š”์†Œ์— `nil`์„ ์ถ”๊ฐ€ํ•ด ์ข…๋ฃŒ ์ง€์ ์„ ๋งŒ๋“ ๋‹ค.
10+
# Complexity
11+
- Time complexity: $O(n)$
12+
- ๋งํฌ๋“œ ๋ฆฌ์ŠคํŠธ์˜ ๊ธธ์ด `n`์— ๋Œ€ํ•˜์—ฌ, ๋งํฌ๋“œ๋ฆฌ์ŠคํŠธ ์ˆœํšŒ์™€ ๋ฐฐ์—ด ์ˆœํšŒ ๋น„์šฉ `n`์ด ๋ฐœ์ƒํ•œ๋‹ค.
13+
- Space complexity: $O(n)$
14+
- ๋งํฌ๋“œ ๋ฆฌ์ŠคํŠธ์˜ ๊ธธ์ด `n`์— ๋Œ€ํ•˜์—ฌ, ๋ฐฐ์—ด(`nodes`) ์ƒ์„ฑ์— ๋น„์šฉ `n`์ด ๋ฐœ์ƒํ•œ๋‹ค.
15+
# Code
16+
## Two Pointer(Deque)
17+
```go
18+
func reorderListv1(head *ListNode) {
19+
nodes := make([]*ListNode, 0, 25)
20+
for curr := head; curr != nil; curr = curr.Next {
21+
nodes = append(nodes, curr)
22+
}
23+
24+
i, j := 0, len(nodes)-1
25+
for i < j {
26+
nodes[j].Next = nodes[i].Next
27+
nodes[i].Next = nodes[j]
28+
29+
i++
30+
j--
31+
}
32+
nodes[i].Next = nil
33+
}
34+
35+
```
36+
37+
## ๋‹ค๋ฅธ ํ’€์ด
38+
: ์†”๋ฃจ์…˜์„ ๋ณด๋ฉฐ ๋’ค์ชฝ ์ ˆ๋ฐ˜์„ `reverse()`ํ•˜์—ฌ ํ•ด๊ฒฐํ•˜๋Š” ์†”๋ฃจ์…˜์ด ๋”์šฑ ์ง๊ด€์ ์œผ๋กœ ๋А๊ปด์กŒ๋‹ค.
39+
40+
```go
41+
func reverse(node *ListNode) *ListNode {
42+
var prev *ListNode
43+
curr := node
44+
for curr != nil {
45+
next := curr.Next
46+
curr.Next = prev
47+
prev = curr
48+
49+
curr = next
50+
}
51+
return prev
52+
}
53+
54+
func reorderList(head *ListNode) {
55+
slow, fast := head, head
56+
for fast != nil && fast.Next != nil {
57+
fast = fast.Next.Next
58+
slow = slow.Next
59+
}
60+
61+
curr, rCurr := head, reverse(slow.Next)
62+
slow.Next = nil
63+
for curr != nil && rCurr != nil {
64+
next, rNext := curr.Next, rCurr.Next
65+
66+
rCurr.Next = next
67+
curr.Next = rCurr
68+
69+
curr, rCurr = next, rNext
70+
}
71+
}
72+
73+
```
74+
: ์ธ๋ฑ์Šค ์กฐ์ ˆํ•˜๋Š” ๊ฒŒ ๊ฝค๋‚˜ ์–ด๋ ค์›Œ์„œ ์†”๋ฃจ์…˜์„ ์ฐธ๊ณ ํ–ˆ๋‹ค...

0 commit comments

Comments
ย (0)