c++ solution


  • 0
    B
    class Solution {
    public:
        bool circularArrayLoop(vector<int>& nums) {
            int n=nums.size();
            if(!n) return false;
            int slow=0, fast=(nums[slow]+n)%n;
            
            while(fast!=slow){
                //if there are different directions
                if(nums[0]*nums[slow]<0 ) return false;
                
                slow=(slow+nums[slow]+n)%n;
                //if fast points to itself 
                if(fast==((fast+nums[fast]+n)%n + nums[(fast+nums[fast]+n)%n] + n)%n) return false;
                
                fast=((fast+nums[fast]+n)%n + nums[(fast+nums[fast]+n)%n] + n)%n;
                
            }
            
            return true;
        }
    };
    

Log in to reply
 

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