0%

141. Linked List Cycle

141. Linked List Cycle

最没技术的做法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* 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
因此,他们必相遇