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
Class Solution {public: int findduplicate (vector<int>& nums) { int min=1,max=nums.size (); while (Min<=max) { int mid= (MIN+MAX)/2; int cnt=0; for (int i=0;i<nums.size (); i++) if (nums[i]<=mid) cnt++; if (cnt>mid) max=mid-1; else min=mid+1; } return min; }};
Binary search ideas, how 1 to N/2 there are duplicates, then 1 to n/2 number of numbers must be greater than N/2 this number itself. The following is the network of other people's ideas, can not understand.
Class Solution {Public:int findduplicate (vector<int>& nums) { int slow = 0; int fast = 0; int finder = 0; while (true) { slow = Nums[slow]; Fast = Nums[nums[fast]]; if (slow = = fast) break ; } while (true) { slow = Nums[slow]; Finder = Nums[finder]; if (slow = = Finder) return slow;} }
If the first number is 0, does it have a dead loop? It seems to be a special case of special thinking.
Leetcode () Find the Duplicate number