Easy to understand 10 line solution Java


  • 0
    F
    public class Solution {
        public int findDuplicate(int[] nums) {
            return helper(nums,0);   
        }
        
        public int helper (int[] nums, int pos) {
            if (nums[pos] == -1)
                return pos;
            int temp = nums[pos];
            nums[pos] = -1;
            return helper(nums,temp);
        }    
    }
    
    

    use nums[pos] to access the array, if already visited (nums[i] == -1) return. otherwise, make as visited and do next iteration.


  • 0
    Y
    This post is deleted!

Log in to reply
 

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