Skip to content

Commit eac930d

Browse files
committed
Solution
Linked List Cycle
1 parent bfe247c commit eac930d

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

β€Žlinked-list-cycle/flynn.goβ€Ž

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* 풀이
3+
* - Floyd's Tortoise and Hare Algorithm을 μ΄μš©ν•œ ν’€μ΄μž…λ‹ˆλ‹€.
4+
* μ°Έκ³ : https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_tortoise_and_hare
5+
*
6+
* Big O
7+
* - N: λ…Έλ“œμ˜ 개수
8+
* - L: 루프 ꡬ간에 μ†ν•˜λŠ” λ…Έλ“œμ˜ 개수
9+
*
10+
* Time Complexity: O(N)
11+
* - 루프가 μ—†λŠ” 경우:
12+
* - fast 포인터가 λ§ν¬λ“œλ¦¬μŠ€νŠΈμ˜ λκΉŒμ§€ μ΄λ™ν•˜λ©΄ μ’…λ£Œν•©λ‹ˆλ‹€.
13+
* - 이 λ•Œ fast ν¬μΈν„°μ˜ 탐색 μ‹œκ°„ λ³΅μž‘λ„λŠ” λ‹€μŒκ³Ό κ°™μŠ΅λ‹ˆλ‹€:
14+
* O(N / 2) = O(N)
15+
* - 루프가 μžˆλŠ” 경우:
16+
* - slow 포인터와 fast 포인터가 루프 μ•ˆμ—μ„œ λ§Œλ‚˜λ©΄ μ’…λ£Œν•©λ‹ˆλ‹€.
17+
* - 이 λ•Œ slow ν¬μΈν„°μ˜ 탐색 μ‹œκ°„ λ³΅μž‘λ„λŠ” λ‹€μŒκ³Ό κ°™μŠ΅λ‹ˆλ‹€:
18+
* O((N - L) + L * c) (cλŠ” slowκ°€ fastλ₯Ό λ§Œλ‚  λ•ŒκΉŒμ§€ 루프λ₯Ό λ°˜λ³΅ν•œ 횟수)
19+
* = O(r + (N - r) * c) (L은 0 <= r <= N인 r에 λŒ€ν•΄ N - r둜 ν‘œν˜„ν•  수 μžˆμŠ΅λ‹ˆλ‹€)
20+
* = O(N)
21+
*
22+
* Space Complexity: O(1)
23+
* - λ…Έλ“œμ˜ κ°œμˆ˜μ— 상관없이 μΌμ •ν•œ 곡간을 μ‚¬μš©ν•©λ‹ˆλ‹€.
24+
*/
25+
26+
/**
27+
* Definition for singly-linked list.
28+
* type ListNode struct {
29+
* Val int
30+
* Next *ListNode
31+
* }
32+
*/
33+
func hasCycle(head *ListNode) bool {
34+
if head == nil {
35+
return false
36+
}
37+
38+
slow := head
39+
fast := head
40+
41+
for fast != nil && fast.Next != nil {
42+
slow = slow.Next
43+
fast = fast.Next.Next
44+
45+
if slow == fast {
46+
return true
47+
}
48+
}
49+
50+
return false
51+
}

0 commit comments

Comments
Β (0)