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

常规解法,暴力破解:

class Solution {
public:
    int arrayNesting(vector<int>& nums) {
        int n = nums.size();
        int res = 0;
        for(int i = 0;i < n;i++)
        {
            int start = nums[i],count = 0;
            do
            {
                start = nums[start];
                count++;
            }while(start != nums[i]);
            
            res = max(res,count);
        }
        
        return res;
    }
};

这种解法提交后提示:

856 / 856 test cases passed, but took too long.
Status: Time Limit Exceeded
Submitted: 6 minutes ago

所有用例都已通过,但时间超过限制。针对上面的方法,可以使用如下优化算法:

class Solution {
public:
    int arrayNesting(vector<int>& nums) {
        int n = nums.size();
        vector<bool> visited(n,false);
        int res = 0;
        for(int i = 0;i < n;i++)
        {
            if(!visited[i])
            {
                int start = nums[i],count = 0;
                do
                {
                    start = nums[start];
                    count++;
                    visited[start] = true;
                }while(start != nums[i]);
                
                res = max(res,count);
            } 
        }
        
        return res;
    }
};

执行结果:

Runtime: 36 ms, faster than 77.76% of C++ online submissions for Array Nesting.
Memory Usage: 30.3 MB, less than 40.35% of C++ online submissions for Array Nesting.

优化的思路是:

例如我们第一遍遍历可以找到5 0 6 2,当我们后面再遍历时就没必要从0 6 2 开始查找了,因为 5 0 6 2就已经算出来最长长度是4.我们可以使用一个vector标记是否需要从这个元素开始遍历。
第二种方法空间复杂度是O(n),我们可以优化空间复杂度为O(1).这里是修改了nums,因为元素范围确定,所以这里使用了INT_MIN(在元素范围之外的值均可以)。

class Solution {
public:
    int arrayNesting(vector<int>& nums) {
        int n = nums.size();
        int res = 0;
        for(int i = 0;i < n;i++)
        {
            if(INT_MIN != nums[i])
            {
                int start = nums[i],count = 0;
                //这里需要格外注意,因为我们改变了vector的值,需要将原来的判断逻辑修改为判断是否等于INT_MIN
                while(INT_MIN != nums[start])
                {
                    int temp = start;
                    start = nums[start];
                    count++;
                    nums[temp] = INT_MIN;
                }
                res = max(count,res);
            } 
        }
        
        return res;
    }
};

优化后的运行结果:

Runtime: 24 ms, faster than 99.65% of C++ online submissions for Array Nesting.
Memory Usage: 30.2 MB, less than 56.82% of C++ online submissions for Array Nesting.