Transmission Door
Description
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.
Ideas
Test Instructions: given an array that contains n + 1 numbers, its value is between 1-n and proves that there is at least one duplicate number. Suppose there is only one duplicate number to find it.
Requirements:
- Assuming that the array is only readable and does not allow the array to be changed
- Space complexity is O (1), time complexity requires less than O (N2)
The following: Because the array is not allowed to be changed, the array cannot be sorted, and because the extra space allows only O (1), the hash is not considered. The complexity cannot be O (N2), so it cannot be solved by brute force.
Method One: In order to reduce the complexity, we can consider two points, reduce the complexity to O (Nlogn), and then iterate through the array to see the number less than or equal to mid, if the number is less than or equal to mid, then the number of repetitions is less than or equal to mid, whereas in the [mid + 1,right] interval.
Method Two: This method uses the principle of Floyd algorithm to solve, can be seen here: click here
class Solution{ Public: //9ms intFindduplicate (vector<int>&Nums) {if(Nums.size ()> 1){intSlow=nums[0],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]; }returnSlow }return -1; }//9ms intFindduplicate (vector<int>&Nums) {intLeft= 1, right=Nums.size ()- 1; while(left<Right- 1){intMid=Left+(Right-Left>> 1);intCnt= 0; for(Auto Val: nums) {if(Val<=MID) CNT++; }if(CNT<=MID) left=MidElseRight=Mid }returnLeft }};
[Leetcode] 287. Find the Duplicate number (Floyd algorithm)