File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You canβt perform that action at this time.
0 commit comments