141. Linked List Cycle Posted on 2021-04-05 Edited on 2022-11-27 In leetcode Disqus: Symbols count in article: 1.1k Reading time ≈ 1 mins. 141. Linked List Cycle 最没技术的做法 12345678910111213141516171819202122/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: bool hasCycle(ListNode *head) { unordered_set<ListNode*> set; while(head) { if(set.emplace(head).second) head = head->next; else return true; } return false; }}; T(n) : O(n) S(n) : O(n) two point nb! explanation 12345678910111213141516171819202122232425/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: bool hasCycle(ListNode *head) { if(!head) return false; ListNode* fast = head; ListNode* slow = head; // 当只有一个节点构成个环时,是可以进入循环,如果没环,就无法进入。就可以处理只有一个的情况 while(fast && fast->next) { fast = fast->next->next; slow = slow->next; if(slow == fast) return true; } return false; }}; 假设slow起始位于N(0),而fast位于N(d - 1)(其中d为一个随机位置) 假设环的长度为M,则t时间后slow位于N(t mod M),而fast位于N((2t + d) mod M) \[\left\{ \begin{aligned} t = pM + x \\ 2t + d = qM + x \end{aligned} \right.\] 两式相减 得到t = (q - p)M - d 因此,他们必相遇