Recursive Solution


  • 0
    R

    Here is my solution

    public class Solution {
    public boolean circularArrayLoop(int[] nums) {
    if(nums==null||nums.length==1)
    return false;

        for(int i=0;i<nums.length;i++){
            List<Integer> list=new ArrayList<Integer>();
            boolean[] visited=new boolean[nums.length]; 
            circular(nums,i,list,visited);
            int res=0;
            for(int v:list){
                res+=v;
                if(res>0&&res%nums.length==0&&list.size()>1)
                    return true;
                
            }
            
        }
        
            
        return false;
        
        
        
        
    }
    
    public void circular(int[] nums,int start,List<Integer> list,boolean[] visited){
        if(visited[start])
            return;
        list.add(nums[start]);
        visited[start]=true;
        int newStart=start+nums[start];
        newStart=newStart<0?nums.length-newStart:newStart;
        newStart=newStart>=nums.length?newStart%nums.length:newStart;
        circular(nums,newStart,list,visited);
    }
    

    }


Log in to reply
 

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