[JAVA] Mark with array / T : O(N), S : O(N)


  • 0
    J
    class Solution {
        public int arrayNesting(int[] nums) {
            int[] marking = new int[nums.length];
            int max = 0;
            for(int i = 0; i < nums.length; i++){
                max = Math.max(max, mark(nums, marking, i, 0));            
            }
            return max;
        }
        
        public int mark(int[] nums, int[] marking, int index, int dist){
            if(marking[index] > 0)
                return Math.max(dist, marking[index]);
            
            marking[index] = 1;
            marking[index] = mark(nums, marking, nums[index], dist+1);
            return marking[index];
        }
    }
    

Log in to reply
 

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