Very simple C++ solution O(n) time O(1) space


  • 0
    T

    The idea here is try to reset the cycle for each i so that nums[i] = i.
    For example, A = [5,4,0,3,1,6,2]
    The cycle for i=0 is 0->5->6->2->0, after reset the cycle, the array become,
    A=[0,4,2,3,1,5,6]

    The code is simple, but the original input array will be changed.

    int arrayNesting(vector<int>& nums) {
            int ans = 1, count=0;
            for(int i = 0; i < nums.size(); count = 0,i++){
                while (i != nums[i]){
                    swap(i, nums[i]); 
                    count++;
                }
                ans = max(ans, count);
            }
            return ans;
        }
    

Log in to reply
 

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