-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path457_Circular Array Loop.java
More file actions
36 lines (33 loc) · 1.08 KB
/
457_Circular Array Loop.java
File metadata and controls
36 lines (33 loc) · 1.08 KB
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
35
36
class Solution {
public boolean circularArrayLoop(int[] nums) {
for (int i = 0; i < nums.length; ++i) {
int slow = i, fast = getNext(i, nums);
if (slow == fast) {
continue;
}
while (nums[fast] * nums[i] > 0 && nums[getNext(fast, nums)] * nums[i] > 0) {
fast = getNext(fast, nums);
fast = getNext(fast, nums);
slow = getNext(slow, nums);
if (slow == fast) {
if (slow == getNext(slow, nums)) {
break;
}
return true;
}
}
slow = i;
int tmp = nums[i];
while (nums[slow] * tmp > 0) {
int next = getNext(slow, nums);
nums[slow] = 0;
slow = next;
}
}
return false;
}
private int getNext(int i, int[] nums) {
int res = (i + nums[i]) % nums.length;
return res >= 0? res: res + nums.length;
}
}