-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcircularArrayLoop.cpp
More file actions
29 lines (27 loc) · 854 Bytes
/
circularArrayLoop.cpp
File metadata and controls
29 lines (27 loc) · 854 Bytes
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
// Source: https://leetcode.com/problems/circular-array-loop/
// Author: Miao Zhang
// Date: 2021-02-13
class Solution {
public:
bool circularArrayLoop(vector<int>& nums) {
int n = nums.size();
for (int i = 0; i < n; i++) {
int slow = i;
int fast = getNext(nums, i);
while (nums[fast] * nums[i] > 0 && nums[getNext(nums, fast)] * nums[i] > 0) {
if (fast == slow) {
if (slow == getNext(nums, slow)) break;
return true;
}
slow = getNext(nums, slow);
fast = getNext(nums, getNext(nums, fast));
}
}
return false;
}
private:
int getNext(vector<int>& nums, int index) {
int n = nums.size();
return ((index + nums[index]) % n + n) % n;
}
};