-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathPC3-CircularArrayLoop.java
34 lines (31 loc) · 1.22 KB
/
PC3-CircularArrayLoop.java
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
class CircularArrayLoop {
public static boolean loopExists(int[] nums) {
// TODO: Write your code here
boolean[] visit = new boolean[nums.length];
for (int i = 0; i < nums.length; i++) {
if (visit[i]) continue;
int fast = next(nums, i);
int slow = i;
while (fast != slow && !visit[fast] && !visit[slow]) {
if (nums[fast] * nums[next(nums, fast)] < 0) break;
fast = next(nums, next(nums, fast));
slow = next(nums, slow);
}
visit[i] = true;
if (slow == next(nums, slow)) {
visit[slow] = true;
continue;
} else if (slow == fast) return true;
}
return false;
}
private static int next(int[]nums, int curr) {
int res = (curr+nums[curr]) % nums.length;
return res >= 0 ? res : res+nums.length;
}
public static void main(String[] args) {
System.out.println(CircularArrayLoop.loopExists(new int[] { 1, 2, -1, 2, 2 }));
System.out.println(CircularArrayLoop.loopExists(new int[] { 2, 2, -1, 2 }));
System.out.println(CircularArrayLoop.loopExists(new int[] { 2, 1, -1, -2 }));
}
}