forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 15
/
circular-array-loop.cpp
40 lines (37 loc) · 1.1 KB
/
circular-array-loop.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Time: O(n)
// Space: O(1)
class Solution {
public:
bool circularArrayLoop(vector<int>& nums) {
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] == 0) {
continue;
}
int slow = i, fast = i;
while (nums[next(nums, slow)] * nums[i] > 0 &&
nums[next(nums, fast)] * nums[i] > 0 &&
nums[next(nums, next(nums, fast))] * nums[i] > 0) {
slow = next(nums, slow);
fast = next(nums, next(nums, fast));
if (slow == fast) {
if (slow == next(nums, slow)) {
break;
}
return true;
}
}
slow = i;
int val = nums[i];
while (nums[slow] * val > 0) {
int tmp = next(nums, slow);
nums[slow] = 0;
slow = tmp;
}
}
return false;
}
private:
int next(const vector<int>& nums, int i) {
return ((i + nums[i]) + nums.size()) % nums.size();
}
};