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 are only one duplicate number, find the duplicate one.
Note:
- You must the Modify the array (assume the array was read only).
- You must use only constant, O(1) Extra space.
- Your runtime complexity should is less than
O(n2)
.
- There is a duplicate number in the array, but it could was repeated more than once.
==============================
Title: If you think of this array as a linked list, the element values in the array as the next pointer in the list node,
We can find out that this problem is the beginning of the ring in the chain list.
A proof of the start node of the ring can be seen here: [http://www.cnblogs.com/li-daphne/p/5551048.html]
=========
Idea: Use the Fast/slow method (the step size of the slow is 2), find the "linked list" Meet the Place,
At this point fast points to the start of the "list", slow then traverse (both fast and slow have a step size of one).
When Fast/slow meets again, it is the "chain-ring" entry, which is the repeating element in the array.
===========
Code:
classSolution { Public: intFindduplicate (vector<int>&nums) { if(Nums.size () >1){ intFast = nums[nums[0]]; intslow = nums[0]; while(slow!=fast) {Slow=Nums[slow]; Fast=Nums[nums[fast]]; } Fast=0; while(Fast! =slow) {Fast=Nums[fast]; Slow=Nums[slow]; } returnslow; } return-1; }};
287. Find the Duplicate number