-
Notifications
You must be signed in to change notification settings - Fork 82
/
Circular Array Loop
35 lines (33 loc) · 1.02 KB
/
Circular Array Loop
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
class Solution {
public:
bool circularArrayLoop(vector<int>& nums) {
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] == 0) {
continue;
}
int back = i, ahead = i;
while (nums[next(nums, back)] * nums[i] > 0 &&
nums[next(nums, ahead)] * nums[i] > 0 &&
nums[next(nums, next(nums, ahead))] * nums[i] > 0) {
back = next(nums, back);
ahead = next(nums, next(nums, ahead));
if (back == ahead) {
if (back == next(nums, back)) {
break;
}
return true;
}
}
back = i;
while (nums[back] * nums[i] > 0) {
nums[back] = 0;
back = next(nums, back);
}
}
return false;
}
private:
int next(const vector<int>& nums, int i) {
return ((i + nums[i]) + nums.size()) % nums.size();
}
};