Java Solution 2 ms


  • 0
    S

    This is my rough code. Please provide comments / suggestions

    public class Solution {
        public boolean circularArrayLoop(int[] nums) {
            if(nums.length < 2){
                return false;
            }
    
    
            int i = 0;
            int j = 0, count = 0;
            boolean rev_flag = false;
    
            while(i < nums.length){
                if(nums[j] == 0){
                    break;
                }
                int temp = j;
                if(i == j && count > 1){
                    return true;
                }
                if(nums[j] < 0){
                    if(j == 0) {
                        j = nums.length - Math.abs(nums[j]);
                        rev_flag = true;
                        count++;
                    } else if(!rev_flag){
                        i++;
                        count = 0;
                        rev_flag = true;
                    } else{
                        j = j - Math.abs(nums[j]);
                        j = j < 0 ? nums.length - Math.abs(j) : j;
                        count++;
                    }
                } else{
                    if(rev_flag){
                        i++;
                        count = 0;
                        rev_flag = false;
                    } else{
                        j = nums[j] + j;
                        count++;
                        j = j > nums.length - 1 ? j - nums.length : j;
                    }
                }
                if(temp == j){
                    i++;
                    count = 0;
                    j = i;
                }
                if(count >= nums.length){
                    return true;
                }
            }
            return false;
        }
    }
    

Log in to reply
 

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