题解
方法1:顺序比较
主要思路
如果一个节点所处位置为n,那么在n之后再遍历n次如果没有遇到这个节点,那么说明这个节点不在环中,证明此点不在环中后,可以将待验证的点移动到目前遍历到的节点的最后一个位置,直到遍历到数组末尾。
源代码:c++
/**
* 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) {
ListNode* old = head;
int count = 1;
int old_index = 1;
while(1)
{
if(head == NULL)
return false;
head = head->next;
count++;
if(head == old)
return true;
if(count >= old_index*2)
{ //说明oldindex所在的位置不在环中,更换监测点
old_index = count;
old = head;
}
}
}
};
时空复杂度
- 用时:8 ms, 在所有 C 提交中击败了93.34%的用户
- 内存:7.8 MB, 在所有 C 提交中击败了91.08%的用户