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:
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}
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].

以例子A = [5,4,0,3,1,6,2]分析:
S[0]={A[0]=5, A[5]=6, A[6]=2, A[2]=0};
S[1]={A[1]=4, A[4]=1};
S[2]={A[2]=0,A[0]=5, A[5]=6, A[6]=2};
S[3]={A[3]=3};
S[4]={A[4]=1, A[1]=4};
S[5]={A[5]=6, A[6]=2,A[2]=0,A[0]=5};
S[6]={A[6]=2, A[2]=0,A[0]=5, A[5]=6};
从上面我们可以发现下面的规律:
1. S[0]包含的元素有{5,6,2,0},与S[5],S[6],S[2]包含的元素相同,
2. 从起始点开始,直到遍历到的值等于起始下标,遍历终止;在这一循环过程中,遍历到的所有元素,其相应的S[k]与起始点的S[k]相同。

class Solution {
public:
    int arrayNesting(vector<int>& nums) {
        int n=nums.size(),cur,start,nxt;
        if(n==0) return 0;
        vector<bool> used(n,false);//用来标记是否遍历过
        int res=0;
        for(start=0;start<n;start++){

            if(used[start]==false)//以遍历过的不用遍历
            {
                int cnt=1;
                cur=start;
                nxt=nums[cur];
                while(nxt!=start){//当重复时终止
                cnt++;
                cur=nxt;
                nxt=nums[cur];
                used[cur]=true;
                }
                res=max(res,cnt);
            }

        }
        return res;
    }
};

空间和时间复杂度均是: O(n) ,

点赞