-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNestingArray.java
42 lines (34 loc) · 987 Bytes
/
NestingArray.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
package org.sean.array;
import java.util.*;
/***
* 565. Array Nesting
*
* N is an integer within the range [1, 20,000].
* The elements of A are all distinct.
* Each element of A is an integer within the range [0, N-1].
*/
public class NestingArray {
public int arrayNesting(int[] nums) {
if (nums == null || nums.length == 0)
return 0;
int length = nums.length;
if (length == 1) {
return 1;
}
int max = 0;
Set<Integer> visitedPositions = new HashSet<>();
for (int i = 0; i < length; i++) {
if (!visitedPositions.contains(i)) {
int elem = nums[i];
int cnt = 0;
while (!visitedPositions.contains(elem)) {
++cnt;
visitedPositions.add(elem);
elem = nums[elem];
}
max = Math.max(max, cnt);
}
}
return max;
}
}