Find the Duplicate number
Total Accepted: 29207 Total Submissions: 74613 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:
The solution is similar to the entry point in the linked list where the ring is found.
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