A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], … } subjected to the rule below.
Suppose the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]… By that analogy, we stop adding right before a duplicate element occurs in S.
Example 1:
Input: A = [5,4,0,3,1,6,2]
Output: 4
Explanation:
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}
循环访问数组元素指向的地方,直到访问到相同元素,问最长的闭环数组长度。
思路:
如果遍历每个元素都找一次闭环,那么会TLE。
可以把遍历过的元素记下来,只对没有访问过的元素查找闭环。
更进一步的做法是,可以看到数组包含的是0~N-1的整数,可以利用这一点,把访问过的元素放到它应该在的位置(对应index处),这样可以看到,一个元素在它本身index的地方,自己就对自己构成闭环,是不会走向下一元素的。这样,访问过的元素所在的闭环,就不会被重复访问了。
public int arrayNesting(int[] nums) {
if(nums == null || nums.length == 0) {
return 0;
}
int result = 0;
for(int i = 0; i < nums.length; i++) {
int cnt = 1;
while(nums[i] != i) {
int tmp = nums[nums[i]];
nums[nums[i]] = nums[i];
nums[i] = tmp;
cnt ++;
}
result = Math.max(result, cnt);
}
return result;
}