算法:环形链表
题目:判断链表是否有环
//环形链表//哈希表 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/
总结
- 上一篇: 算法:恢复二叉搜索树
- 下一篇: 算法:串联所有单词的子串