First time share my code, using hashset. only beats around 25%


  • 0
    M

    Since the elements are all above 0, once I visited an element, I reassign -1 to it.
    advice and criticize are both welcome.

    public int arrayNesting(int[] nums) {
          int max = 0;	
    		for(int i =0;i<nums.length;i++)
    		{
    			Set<Integer> myset = new HashSet<Integer>();
    			do{
    				int index = nums[i];
    				if(index == -1 || myset.contains(nums[i]))
    					break;
    				else
    				{
    					myset.add(nums[i]);
    					nums[i] = -1; // since the elements are all above 0, once I visit one element
    //					I reassign -1 to it, meaning that this one has already been visited
    					i = index;  // update i to keep visiting to avoid recursive.
    				}
    			}while(i!=-1); // as long as the next index I am visiting has not been visited.
    			max = Math.max(max, myset.size());
    		}
    		return max;
    

Log in to reply
 

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