You are given an array of positive and negative integers. If anumber n at an index is positive, then move forward n steps. Conversely, ifit's negative (-n), move backward n steps. Assume the first element of thearray is forward next to the last element, and the last element is backwardnext to the first element. Determine if there is a loop in this array. A loopstarts 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 isguaranteed to contain no element "0".
Can you do it in O(n) time complexity and O(1) space complexity?
这题还是相当有难度的,难就难在要求O(n)的时间和O(1)的空间,
这一题我使用了快慢指针解决的,首先遍历一遍原数组,对于数组里面的每一个数值,设定一个slow指针,和一个fast指针,slow指针每一次跳一格,fast指针每一次跳两格,当slow指针第一次跳时回到了原点,说明这个起点不可行,将nums[start]设置为0,当fast指针跳到了一个格子,格子的值和fast指针跳之前的格子的值符号相反的时候,说明从start格子到fast指针所在的格子都不可行,需要将从start格子到fast指针格子的全部格子都设置为0,这里使用的是setZero函数
这里还需要注意的是当fast跳两步之后和跳之前的索引相等的话,说明fast指针找到了一个单循环,单循环不能够算作循环,因此这个时候依然需要将start到fast指针之间的全部格子都设为0
当某一次fast和slow指针索引相等的时候,说明这个时候找到了一个非单循环,这个循环是合理的,因此说明这个数组里面存在循环,返回true
以后在做题的时候记住使用快慢指针判断路径里面是否存在循环的方法,使用一个快指针,一个慢指针,快指针没次移动两个,慢指针每次移动一格,当快指针和慢指针移动到索引相等的时候,说明找到了一个循环。这里需要说明一下,只要路径中存在循环,在不断的移动的过程中快指针最终一定会和慢指针相等,也就是说只要存在循环则一定可以找到
class Solution {
public:
int theNext(vector<int>& nums, int mark, int index,int n)
{
if (index == -1) return -1;
int tmp= (index + nums[index] + n) % n;
if (nums[tmp] * mark < 0) return -1;
return tmp;
}
void setZero(int start, int end, vector<int>& nums,int n)
{
int tmp;
int next = (start + nums[start]+n)%n; nums[start] = 0;
while (next != end)
{
tmp = next;
next = (next + nums[tmp]+n)%n;
nums[tmp]=0;
}
nums[next] = 0;
}
bool circularArrayLoop(vector<int>& nums) {
int n = nums.size(); int pr, prr, tmp, start;
for (int i = 0; i < n; i++)
{
start = i;
if (nums[i] == 0) continue;
pr = theNext(nums, 0, i, n);
if (pr == start || pr == -1 || nums[pr] == 0) { nums[i] = 0; continue; }
prr= theNext(nums, nums[pr], pr, n);
if (prr == -1 || nums[pr] == 0) { setZero(start, pr, nums,n); continue; }
while (1)
{
for (int j = 0; j < 2; j++)
{
tmp = theNext(nums, nums[prr], prr, n);
if (tmp == -1 || nums[tmp] == 0 || tmp==prr) {
setZero(start, prr, nums,n);
goto theNext; }
prr = tmp;
}
tmp = theNext(nums, nums[pr], pr, n);
if (tmp == prr) return true;
pr = tmp;
}
theNext:;
}
return false;
}
};