circular-array-loop
1.0.0
Circular Array Loop
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1
#include <bits/stdc++.h>
2
3
using namespace
std;
4
5
class
Solution
6
{
7
private
:
8
int
get_next_index
(
int
index,
int
direction, vector<int>& nums)
9
{
10
int
n = (int)nums.size();
11
int
next_index = (index + nums[index]) % n;
12
while
(next_index < 0)
13
next_index += n;
14
int
next_direction = 1;
15
if
(nums[next_index] < 0)
16
next_direction = -1;
17
18
// cycle is only valid when pointers move in the same direction; 1 element cycles do not count
19
if
(direction != next_direction || index == next_index)
20
return
-1;
21
22
return
next_index;
23
}
24
25
public
:
26
bool
circularArrayLoop
(vector<int>& nums)
27
{
28
set<int> visited;
29
int
size = (int)nums.size();
30
31
// start from each elements of nums
32
for
(
int
i = 0; i < size; ++i)
33
{
34
// do not check inclusive paths
35
if
(visited.find(i) != visited.end())
36
continue
;
37
38
int
slow = i, fast = i;
39
int
direction = 1;
40
if
(nums[i] < 0)
41
direction = -1;
42
43
while
(1)
44
{
45
visited.insert(slow);
46
visited.insert(fast);
47
slow =
get_next_index
(slow, direction, nums);
48
fast =
get_next_index
(fast, direction, nums);
49
if
(slow == -1 || fast == -1)
50
break
;
51
52
fast =
get_next_index
(fast, direction, nums);
53
if
(fast == -1)
54
break
;
55
56
if
(slow == fast)
57
return
true
;
58
}
59
}
60
return
false
;
61
}
62
};
63
64
int
main
()
65
{
66
vector<int> array = {-1,-2,-3,-4,-5,6};
// expected false
67
cout <<
"output: "
<<
Solution
().
circularArrayLoop
(array) << endl;
68
return
0;
69
}
Solution
Definition
main.cpp:6
Solution::get_next_index
int get_next_index(int index, int direction, vector< int > &nums)
Definition
main.cpp:8
Solution::circularArrayLoop
bool circularArrayLoop(vector< int > &nums)
Definition
main.cpp:26
main
int main()
Definition
main.cpp:64
main.cpp
Generated by
1.9.8