##此问题 Test Case并不完全,暂时AC。
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?
C++代码片:
class Solution {
public:
bool circularArrayLoop(vector& nums) {
//vector check(nums.size(),false);
for(int i=0; i0&&nums.at(i)*nums.at(fast)>0&&nums.at(i)*nums.at(move(nums,fast))>0)
{
slow = move(nums,slow);
fast = move(nums,move(nums,fast));
if(slow == fast)
{
if(slow==move(nums,slow)) break;
else return true;
}
}
slow = i;
while(nums.at(i)*nums.at(slow)>0)
{
nums.at(slow) = 0;
slow = move(nums,slow);
}
}
return false;
}
int move(vector& nums, int i)
{
int n = nums.size();
return ((i+nums.at(i)>=0) ? ((i+nums.at(i))%n) : ((i+nums.at(i))%n)+n);
}
};