circular-array-loop 1.0.0
Circular Array Loop
Loading...
Searching...
No Matches
Solution Class Reference

Public Member Functions

bool circularArrayLoop (vector< int > &nums)
 

Private Member Functions

int get_next_index (int index, int direction, vector< int > &nums)
 

Detailed Description

Definition at line 5 of file main.cpp.

Member Function Documentation

◆ circularArrayLoop()

bool Solution::circularArrayLoop ( vector< int > &  nums)
inline

Definition at line 26 of file main.cpp.

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 }
int get_next_index(int index, int direction, vector< int > &nums)
Definition main.cpp:8

References get_next_index().

Referenced by main().

◆ get_next_index()

int Solution::get_next_index ( int  index,
int  direction,
vector< int > &  nums 
)
inlineprivate

Definition at line 8 of file main.cpp.

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 }

Referenced by circularArrayLoop().


The documentation for this class was generated from the following file: