565. nested arrays
Index is zero length N of array A, containing 0 to N - 1 of all integers. Find and return the largest collection of S, S [i] = {A [i], A [A [i]], A [A [A [i]]], ...} and observe the following rules.
Assumed that the selection element of index i A [i] is the first element of S, S of the next element A should be [A [i]], followed by A [A [A [i]]] ... and so on , keep adding until repetition of elements of S appear.
Example 1:
Input: A = [5,4,0,3,1,6,2]
Output: 4
explained:
A [0] =. 5, A [. 1] = 4, A [2] = 0, A [. 3] = 3, A [4] = 1 , A [5] = 6, A [6] = 2.
One of the longest S [K]:
S [0] = {A [0], A [. 5], A [. 6], A [2] = {}. 5,. 6, 2, 0}
Note:
N is an integer between [1, 20,000].
A does not contain duplicate elements.
A size of the element in the [0, N-1] between.
class Solution {
public int arrayNesting(int[] nums) {
int max = 0;
for (int i = 0; i < nums.length; i++) {
int cnt = 0;
for (int j = i; nums[j] != -1; ) {
cnt++;
int t = nums[j];
nums[j] = -1;
j = t;
}
max = Math.max(max, cnt);
}
return max;
}
}