forked from larissalages/code_problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularArrayLoop.java
More file actions
43 lines (38 loc) · 1.19 KB
/
CircularArrayLoop.java
File metadata and controls
43 lines (38 loc) · 1.19 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
37
38
39
40
41
42
43
/**
* Problem : https://leetcode.com/problems/circular-array-loop/submissions/
* Time Complexity : O(n)
* Space Complexity : O(1)
*/
public class CircularArrayLoop {
public boolean circularArrayLoop(int[] nums) {
int N = nums.length;
int K = 1001;
for (int i=0; i<N; i++) {
if (nums[i]>1000 || nums[i]<-1000)
continue;
boolean direction = (nums[i]>0);
int ix=i;
int nextIndex;
while (true) {
nextIndex = getNextIndex(nums, ix);
if(
(nums[nextIndex]>1000 && nums[nextIndex]!=K) || (nums[nextIndex]<-1000 && nums[nextIndex]!=-K) ||
nextIndex==ix || nums[nextIndex]>0)!=direction {
break;
}
if(nums[nextIndex]==(direction?K:-K)){
return true;
}
nums[ix] = (direction?K:-K);
ix = nextIndex;
}
K+=1;
}
return false;
}
private int getNextIndex(int[] nums, int i) {
int N = nums.length;
int out = (nums[i] + i)%N;
return (out>=0)?out:(out+N);
}
}