Skip to content

Commit 65646f5

Browse files
author
Hieu Luong
committed
Solve Problem 457 - Circular Array Loop
1 parent 35ad72d commit 65646f5

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package twopointers;
2+
3+
public class Problem457_CircularArrayLoop {
4+
5+
public boolean circularArrayLoop(int[] A) {
6+
for (int i = 0; i < A.length; i++) {
7+
if (A[i] == 0) continue;
8+
int a = A[i];
9+
10+
int slow = i, fast = next(A,i);
11+
while (same(a, A[fast]) && same(a, A[next(A, fast)])) {
12+
if (slow == fast) {
13+
if (slow == next(A, slow)) break;
14+
return true;
15+
}
16+
slow = next(A, slow);
17+
fast = next(A, next(A, fast));
18+
}
19+
20+
slow = i;
21+
while (same(a, A[slow])) {
22+
int tmp = next(A, slow);
23+
A[slow] = 0;
24+
slow = tmp;
25+
}
26+
}
27+
return false;
28+
}
29+
30+
private int next(int[] A, int i) {
31+
int n = A.length, j = (i + A[i]) % n;
32+
return (j >= 0) ? j : j+n;
33+
}
34+
35+
private boolean same(int a, int b) {
36+
if (a > 0 && b > 0) return true;
37+
if (a < 0 && b < 0) return true;
38+
return false;
39+
}
40+
}

0 commit comments

Comments
 (0)