287. Find the Duplicate Number!

class Solution {
    public int findDuplicate(int[] nums) {
        // observation: 0<nums[i]<nums.length
        // array can be used to represent a linkedList by vaule-index
        // i.e. node at index i point to the node at index nums[i]
        // the duplicate number will be point to the same node (intersection)
        
        
        // slow, fast refer to the index
        int slow = nums[0];
        int fast = nums[0];
        
        do{
            slow= nums[slow];
            fast = nums[nums[fast]];
        }while(slow!=fast);
        //now slow and fast are the same (as index)
        
        int startA = nums[0];
        int startB = slow;
        while(startA!=startB){
            startA = nums[startA];
            startB = nums[startB];
        }
        return startA;
    }
}

Last updated