C++ easy and short O(n) solution


  • 0
    M
        int arrayNesting(vector<int>& nums) {
            unordered_set<int> visited;
            int res=0, temp=0, cur=0;
            for(int i=0;i<nums.size();i++) {
                if(visited.find(nums[i])!=visited.end()) continue;
                cur=i, temp=0;
                while(visited.find(nums[cur])==visited.end()) { 
                    temp++;
                    visited.insert(nums[cur]);
                    cur=nums[cur];
                }
                res=max(res, temp);
            }
            return res;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.