Java - Simple DFS/visited style soln. beats > 90%


  • 0
    V
    public class Solution {
        public int arrayNesting(int[] nums) {
            int[] visited = new int[nums.length];
            int max = Integer.MIN_VALUE;
            for(int i=0; i<nums.length; i++) {
                if(visited[i] == 0) {
                    int count = 1;
                    int pointer = nums[i];
                    visited[i] = 1;
                    while(pointer != i) {
                        visited[pointer] = 1;
                        count++;
                        pointer = nums[pointer];
                    }
                    max = Math.max(max, count);
                    if(max == nums.length) return max;
                }
            }
            return max;
        }
    }
    

Log in to reply
 

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