LeetCode -- Find the Duplicate Number
Problem description:
Given an array nums containing n + 1 integers where each integer is between 1 and n (random SIVE), prove that at least one duplicate number must exist. assume that there is only one duplicate number, find the duplicate one.
Note:
You must not modify the array (assume the array is read only ).
You must use only constant, O (1) extra space.
Your runtime complexity shocould be less than O (n2 ).
There is only one duplicate number in the array, but it cocould be repeated more than once.
Find the duplicate one in an array.
Because the question limits the space that can only be used for O (1), and the parameter array cannot be modified.
Therefore, it cannot be sorted, nor can it create a tag array to traverse at a time to fill in the blanks. In addition, because repeated elements can appear multiple times, it is impossible to use the formula summation of the differential series => s, use arrays and-s.
I found a solution, which is quite clever. The idea is similar to that: Find the ring in a linked list and find the location of the ring.
1. The speed pointer is used.
2. Starting from the position where the fast and slow pointers meet, the slow pointer and the other pointer starting from the starting position take one step each time until they meet, that is, where the duplicate node occurs.
Implementation Code:
public class Solution { public int FindDuplicate(int[] nums) { // define slow and fast , fast each time move 2 times var slow = 0; var fast = 0; while(true) { slow = nums[slow]; fast = nums[nums[fast]]; if(slow == fast){ break; } } // now, lets create another pointer 'finder' from the start position. // slow will stay where it is. // finder and slow each time move one step. next time this meet is where duplicate happens var finder = 0; while(true) { slow = nums[slow]; finder = nums[finder]; if (slow == finder){ return slow; } } }}