题目描述:
You are given an array of positive and negative integers. If a number n at an index is positive, then move forward n steps. Conversely, if it's negative (-n), move backward n steps. Assume the first element of the array is forward next to the last element, and the last element is backward next to the first element. Determine if there is a loop in this array. A loop starts and ends at a particular index with more than 1 element along the loop. The loop must be "forward" or "backward'.
Example 1: Given the array [2, -1, 1, 2, 2], there is a loop, from index 0 -> 2 -> 3 -> 0.
Example 2: Given the array [-1, 2], there is no loop.
Note: The given array is guaranteed to contain no element "0".
Can you do it in O(n) time complexity and O(1) space complexity?
以当前元素的数值作为前进或者后退的步数,遍历到下一个元素,而且要求在一个环中必须全部是前进或者全部是后退,按照以上的遍历规则,求问数组中是否存在环,要求O(n)的时间复杂度和O(1)的空间复杂度。
class Solution {
public:
bool circularArrayLoop(vector<int>& nums) {
int n=nums.size();
if(n<=1) return false;
for(int i=0;i<n;i++)
{
int slow=i;
int fast=i;
while(nums[slow]*nums[i]>0&&nums[fast]*nums[i]>0&&nums[next(nums,slow)]*nums[i]>0)
{
//在该循环中不可以对已访问的元素进行标记,否则改变元素值之后
//接下来的移动就会错误,所以这个循环只判断从i开始是否有环
slow=next(nums,slow);
fast=next(nums,fast);
fast=next(nums,fast);
if(slow==fast)
{
if(slow==next(nums,slow)) break;//由于环最少需要2个元素,自身循环不是环,例如[1,2]
else return true;
}
}
//从i开始无环,对访问过的元素标记为0,这样下一次访问这个元素一定会跳过
//因为从i开始访问的元素都不可能形成环
slow=i;
while(nums[slow]*nums[i]>0)//移动方向必须同向
{
nums[slow]=0;
slow=next(nums,slow);
}
}
return false;
}
int next(vector<int> nums, int i)
{
int n=nums.size();
if((nums[i]+i)<0) return nums[i]+i+n;
else return (nums[i]+i)%n;
}
};