[LeetCode] 142. Linked List Cycle II
来源:互联网 发布:计数排序算法 编辑:程序博客网 时间:2024/06/05 19:42
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
/*该题在第一题的基础之上,要求检测出循环的入口处。检测循环的算法,同第一题,核心思想就是一个跑的快的人,一个跑的慢的人,结局无非是跑的快的人先到达终点(无循环存在),或是跑的快的人追上了跑的慢的人(循环存在)。令L1表示从出发点到循环入口处的距离令L2表示从循环入口处到快慢二人碰面处的距离令C表示循环的长度令n1, n2分别表示二人在循环内所绕的圈数则慢的人跑的距离为 L1 + L2 + n1 * C快的人跑的距离为 L1 + L2 + n2 * C同时,由于快的人的速度是慢的人的两倍,可得下式2(L1 + L2 + n1 * C) = L1 + L2 + n2 * C即L1 = (n2 - n1 - 1) * C + (C - L2)也就是说,从出发处到循环入口处的距离和从碰面处到循环入口处的距离(当然这中间可能绕了好多犬)是相等的。简单来说,一个人从出发处出发,一个人从循环碰面处出发,以同样的速度前进,那么最终二者必将会在循环入口处相遇。*/class Solution {public: ListNode *detectCycle(ListNode *head) { if (head == nullptr || head->next == nullptr) return nullptr; ListNode *slow = head, *fast = head; while (fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) { ListNode *entry = head; while (slow != entry) { slow = slow->next; entry = entry->next; } return entry; } } return nullptr; }};
阅读全文
0 0
- [LeetCode]141. Linked List Cycle【&142. Linked List Cycle II】
- leetcode--141. Linked List Cycle&&142. Linked List Cycle II
- LeetCode 141. Linked List Cycle && 142. Linked List Cycle II
- 142. Linked List Cycle II leetcode list
- LeetCode 142. Linked List Cycle II
- [LeetCode]142.Linked List Cycle II
- [leetcode] 142.Linked List Cycle II
- [leetcode] 142. Linked List Cycle II
- leetcode 142. Linked List Cycle II
- [Leetcode]142. Linked List Cycle II @python
- [LeetCode]142. Linked List Cycle II
- 142. Linked List Cycle II LeetCode
- LeetCode:142. Linked List Cycle II
- LeetCode--142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode *** 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- 进程管理
- Altium Designer 10 下载,安装和破解
- 使用JAVA程序解析XML(dom4j+xpath)
- xargs用法详解
- 判定表法设计测试用例
- [LeetCode] 142. Linked List Cycle II
- Redis 命令大全
- MySQL命名、设计及使用规范
- java程序员的python之路(函数)
- idea新建web项目
- 备件仓库管理系统
- 3.React中文之渲染元素。
- log4j的logger继承性
- Hello_TensorFlow!