数组中的环路
题目出处:https://leetcode-cn.com/problems/circular-array-loop/
思路:类似于链表中找是否存在环路,定义两个指针(一个快指针、一个慢指针),快指针初始时在慢指针的下一个位置。每次慢指针走一步、快指针走两步,两者相遇时则证明存在环。
题干中的限制条件:
- 环的长度为1:在环的某一处结点判断(快慢指针相遇处为环的结点),如果此时慢指针的下一个位置还是它本身,则说明环的长度为1。
- 环中的每个元素的方向一致:判断快指针的每一个位置的方向是否与初始方向一致,且快指针下一个位置的方向也与初始位置的方向一致。
class Solution {
public:
int next(vector<int>& nums, int now){ //下一步的位置
int n = nums.size();
int next_pos = ((now + nums[now]) % n +n) % n;
return next_pos;
}
bool circularArrayLoop(vector<int>& nums) {
int n = nums.size();
for(int i = 0; i < n; ++i){
int slow = i; int fast = next(nums, slow); // 快指针多走一步
while(nums[fast]*nums[slow] > 0 && nums[next(nums,fast)]*nums[slow] > 0){ //快指针判断方向是否一直
if(slow == fast){ //快慢指针相遇
if(slow == next(nums, slow)){ //环的长度为1,继续找环
break;
}
else{ //环的长度不为1,说明存在环,直接返回true
return true;
}
}
slow = next(nums, slow); //慢指针走一步
fast = next(nums, next(nums,fast)); //快指针走两步
}
}
return false;
}
};
链表中的环路
题目出处:https://leetcode-cn.com/problems/linked-list-cycle/
/**
* 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 || !head->next){
return false;
}
ListNode* slow = head;
ListNode* fast = head->next;
while(fast && fast->next){
if(slow == fast){
return true;
}
slow = slow->next;
fast = fast->next->next;
}
return false;
}
};