Find the Duplicate number
Total Accepted: 26713 Total Submissions: 68841 Difficulty: Hard
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.
Credits:
Special thanks to @jianchao. Li.fighter for adding the problem and creating all test cases.
Subscribe to see which companies asked this question
Hide TagsBinary Search Array of pointersHide Similar Problems(H) First Missing Positive (m) single number (m) Linked List Cycle II (m) Missing number
Ideas:
(1) Take a direct look at an example
Index:0 1 2 3 4 5 6 7 8
Nums:2 1 4 7 5 6 4 3 8
(2) starting from index = 0, you can see that there is a loop:
6->, 4, 2, 6, index:0, .....
Nums[index]: 2, 4, 5, 6, 4-> .....
(3) can be seen from [4->5->6->4] is a loop, exactly 4 is the duplicate number we requested.
Is it a bit like: The entry point of the Linked list Cycle II in the Find ring.
C + + code:
Class Solution {public: int findduplicate (vector<int>& nums) { int size = Nums.size (); if (Size < 2) return-1; int slow = nums[0]; int fast = Nums[nums[0]]; while (slow! = fast) { slow = Nums[slow]; Fast = Nums[nums[fast]]; } Fast = 0; while (slow! = fast) { slow = Nums[slow]; Fast = Nums[fast]; } return slow;} ;
Leetcode:find the Duplicate number