my 1ms java solution and explantion


  • 0
    L

    key point : if we have sum(nums[i1],nums[i2],nums[i3]) equals the n * nums.length(n >=1) there is loop in the array. buf if we had move all the element in the array there is still no sum(nums[i1],nums[i2],nums[i3]) equals the n * nums.length there is no loop in the array,because we had back to start index again.

     public boolean circularArrayLoop(int[] nums) {
        if(nums.length < 2) return false;
        int count = 0,sum = 0,len = nums.length;
        for(int i =0; i < len - 1; i++){
            int j = i;count = 0; sum = 0;
            for(;;){
                if(sum * nums[j] < 0){
                    break;
                }
                if(sum % len == 0 && count > 1) return true;
                if(count > len){
                    break;
                }
                sum += nums[j];
                j+=nums[j];
                if(j >= 0) j %= len;
                else j += len;
                count++;
            }
        }
        return false;
    }

Log in to reply
 

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