Find the Duplicate Number

Question:

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Note:

1.You must not modify the array (assume the array is read only).

2.You must use only constant, O(1) extra space. Your runtime complexity should be less than O(n2).

3.There is only one duplicate number in the array, but it could be repeated more than once.


Analysis:

If we can modify the array, we can use the connection between array index and array's number to find the duplicate number since the array's index ranges in [0,n] and the numbers are among [1,n].

But in this problem, we are not allowed to do this.

Take a look at the numbers in the array, there are n+1 numbers in range [1,n]. What if we follow the chain 0->num[0]->num[num[0]]->num[num[num[0]]]->...

suppose num is [2,1,2,3,4], follow the chain we have 0->2->2. the links has a cycle and the start node of cycle is the duplicated number.

suppose num is [3,6,2,5,4,1,2,7], follow the chain we have 0->5->1->2->2. the cycle also meet start at the duplicated number.

So we can use the same algorithm we used to detect the cycle and find the start node of cycle in Linked List.

Solution

 public int findDuplicate(int[] nums) {
        if(nums==null || nums.length<2) return -1;
        int slow=nums[0], fast=nums[slow];
        while(slow!=fast){
            slow=nums[slow];
            fast=nums[nums[fast]];
        }
        slow=0;
        while(slow!=fast){
            slow=nums[slow];
            fast=nums[fast];
        }
        return slow;
    }

results matching ""

    No results matching ""