Neat recursive solution C++


  • 0
    S
        int N;
    
        bool dodfs(vector<int> &nums, int i, bool pos)
        {
            if (nums[i] < 0 and pos) return false;
            if (nums[i] > 0 and !pos) return false;
            if (nums[i] == 0) return true;
            
            int nxt = ((i + nums[i]) % N + N) % N;
            int t = nums[i];
            
            nums[i] = 0;
            if (nxt != i)
                if(dodfs(nums, nxt, pos))
                    return true;
            
            nums[i] = t;
            return false;
        }
    
        bool circularArrayLoop(vector<int>& nums) {
            
            N = nums.size();
            
            for (int i = 0; i < nums.size(); i++)
                if (dodfs(nums, i, (nums[i] > 0)))
                    return true;
            
            return false;
        }
    

Log in to reply
 

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