问题描述
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?
题目链接:
思路分析
给一个数组,里面元素非零。如果元素是正数就前进n步,反之如果是负数就后退n步。数组是首尾相连循环的。loop中元素个数要大于1,判断数组中是否存在loop。
类似于链表的环的问题,只不过是存放在数组中了而已。创建一个计算下一个位置的函数getIndex,判断有无向左过0的情况,计算得到不同的index。
然后开始从第一个数字开始循环,我们会将判定为不同的path的元素都设为0,所以要先判断一下。然后用两个快慢指针,从i处开始循环,(注意要判断快指针的两次跳跃都是合法的)只要循环的方向不变,也就是nums的值符号是相同的,就继续循环。总会有slow和fast碰上的时候,这时要判断是否是只有一个元素的循环,是的话breakk,如果不是就可以返回true了。
对于快慢指针循环之后,要将之前这条不同的循环上的节点都置0,循环条件同样是nums的值要同符号,防止再次进入这条路径。这也是我们for循环中要判0的原因。
代码
class Solution {
public:
bool circularArrayLoop(vector<int>& nums) {
for (int i = 0; i < nums.size(); i++){
if (nums[i] == 0)
continue;
int slow = i;
int fast = getIndex(slow, nums);
while (nums[i] * nums[fast] > 0 && nums[i] * nums[getIndex(fast, nums)] > 0){
if (slow == fast){
if (slow == getIndex(slow, nums))
break;
return true;
}
slow = getIndex(slow, nums);
fast = getIndex(getIndex(fast, nums), nums);
}
slow = i;
int val = nums[slow];
while(nums[slow] * val > 0){
int next = getIndex(slow, nums);
nums[slow] = 0;
slow = next;
}
}
return false;
}
int getIndex(int i, vector<int>& nums){
int n = nums.size();
return i + nums[i] >= 0? (i + nums[i]) % n : n + ((i + nums[i]) % n);
}
};
时间复杂度:
O(n)
空间复杂度:
O(1
反思
java和c++的模除不同于python的模除,python中模除的结果永远是非负的,而c++则是可以为负数的,这也是我们计算index的基础。