算法:环形链表
?題目:判斷鏈表是否有環
//環形鏈表//哈希表 func hasCycle(head *ListNode) bool {seen := map[*ListNode]struct{}{}for head != nil {if _, ok := seen[head]; ok {return true}//標記該節點已被訪問seen[head] = struct{}{}head = head.Next}return false }//快慢指針 func hasCycle(head *ListNode) bool {if head == nil || head.Next == nil {return false}slow, fast := head, head.Nextfor fast != slow {if fast == nil || fast.Next == nil {return false}//慢指針一次移動2步slow = slow.Next//快指針一次移動2步fast = fast.Next.Next}return true }鏈接:https://leetcode-cn.com/problems/linked-list-cycle/solution/huan-xing-lian-biao-by-leetcode-solution/
總結
- 上一篇: 算法:恢复二叉搜索树
- 下一篇: 算法:串联所有单词的子串