-
Notifications
You must be signed in to change notification settings - Fork 0
/
LoopFinder.java
60 lines (45 loc) · 969 Bytes
/
LoopFinder.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package Google
/**
* Count number of array elements in an array containing a loop
*/
public class LoopFinder {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int numbers[] = {1,2,1};
int count = findLoop(numbers);
System.out.println("count: " + count);
}
/**
* @param numbers
*/
private static int findLoop(int[] numbers) {
int count = 0;
int i = 0;
// get cycle start
while(numbers[i] > 0){
int prevIndex = i;
i = numbers[i];
numbers[prevIndex] = -1 * numbers[prevIndex];
}
// get count
int startOfArray = i;
do{
count++;
i = numbers[Math.abs(i)];
}while(Math.abs(i) != startOfArray);
return count;
}
/**
* @param numbers
*/
private static void printArray(int[] numbers) {
// TODO Auto-generated method stub
for(int i=0;i<numbers.length;i++){
System.out.print(", " + numbers[i]);
}
System.out.println(" ");
}
}