LeetCode 565. Array Nesting
A zero-indexed array A consisting of N different integers is given. The array contains all integers in the range [0, N - 1].
Sets S[K] for 0 <= K < N are defined as follows:
S[K] = { A[K], A[A[K]], A[A[A[K]]], … }.
Sets S[K] are finite for each K and should NOT contain duplicates.
Write a function that given an array A consisting of N integers, return the size of the largest set S[K] for this array.
Example 1:
1 | Input: A = [5,4,0,3,1,6,2] |
Note:
- N is an integer within the range [1, 20,000].
- The elements of A are all distinct.
- Each element of array A is an integer within the range [0, N-1].
以数组中的当前元素值作为下一个下标,依次访问直到到达一个已经访问过的元素。类似于构造一个链表。
因为数组中的元素是连续的而且不重复,所以不存在多个元素指向同一个下标。所以最后得到的一定是一个或者多个循环链表的结构。
因此遍历数组,从每个元素开始构造到结束,把遍历过的所有位置设为-1表示访问过不用再处理,记录得到的最大长度。
1 | class Solution { |