敘述
這是 Data Structure I 的第八天第一個題目,總共有三題。
- 難度:
Easy - 花費時間: 2小時
- 題目
傳入一個 Linked List 的 head ,判斷這個 Linked List 是否循環(某個 next 指到前面的 val)
如果他有迴圈就回傳 true ,如果沒有就回傳 false 。
點我開啟限制與範例
限制:
- The number of the nodes in the list is in the range
[0, 104]. -105 <= Node.val <= 105posis-1or a valid index in the linked-list.
Example 1:
1 | Input: head = [3,2,0,-4], pos = 1 |
Example 2:
1 | Input: head = [1,2], pos = 0 |
Example 3:
1 | Input: head = [1], pos = -1 |
筆記
使用 Two Pointers 就可以解決這個問題,但是我沒有想到 Two Pointers 的寫法,我很抱歉 TAT
複雜度
Two Pointers:
- 時間複雜度: O(n)
- 空間複雜度: O(1)
Hash Table
- 時間複雜度: O(n)
- 空間複雜度: O(n)
我用的 Hash Table 寫出了兩種不同的程式碼,但都成績很差,因為 Two Pointers 算這題的正解, Hash Table 只能算是可以寫。
解題思路也非常清晰易懂,遍歷一次陣列然後同時檢查 head 是否有在 Hash Table 裡,步驟如下:
- 遍歷陣列:
- 檢查
head跟head.next是否存在:- 只要一個不存在 >
return false
- 只要一個不存在 >
- 檢查
head是否有在Hash Table:- 如果有 >
return true代表有迴圈。
- 如果有 >
- 把
head放入Hash Table - 把
head指向head.next
- 檢查
程式碼
Iterate Style
1 | /** |
Recursive Style
1 | /** |
成績
