forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
29 lines (28 loc) · 885 Bytes
/
Solution.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
class Solution {
public:
bool circularArrayLoop(vector<int>& nums) {
int n = nums.size();
for (int i = 0; i < n; ++i) {
if (!nums[i]) continue;
int slow = i, fast = next(nums, i);
while (nums[slow] * nums[fast] > 0 && nums[slow] * nums[next(nums, fast)] > 0) {
if (slow == fast) {
if (slow != next(nums, slow)) return true;
break;
}
slow = next(nums, slow);
fast = next(nums, next(nums, fast));
}
int j = i;
while (nums[j] * nums[next(nums, j)] > 0) {
nums[j] = 0;
j = next(nums, j);
}
}
return false;
}
int next(vector<int>& nums, int i) {
int n = nums.size();
return (i + nums[i] % n + n) % n;
}
};