There is mainly, solutions to solve, this problem.
The first one is very clever, using the idea of the cycle detection, and runs in O (n) time. Refer to this post, whose code is rewritten below.
1 classSolution {2 Public:3 intFindduplicate (vector<int>&nums) {4 intn = nums.size (), slow = n-1, fast = N-1;5 Do {6slow = Nums[slow]-1;7Fast = Nums[nums[fast]-1] -1;8} while(Slow! =fast);9Fast = N-1; Ten Do { Oneslow = Nums[slow]-1; AFast = Nums[fast]-1; -} while(Slow! =fast); - returnSlow +1; the } -};
The second one uses binary search to search for possible numbers in ranges [1, N] and eliminate one half at each Time. You could refer to this nice post for a good explanation. The code is rewritten below in C + +.
1 classSolution {2 Public:3 intFindduplicate (vector<int>&nums) {4 intn = nums.size (), L =1, R = N-1;5 while(L <r) {6 intm = L + ((r-l) >>1);7 intCNT =Notgreaterthan (Nums, m);8 if(CNT <= m) L = m +1;9 ElseR =m;Ten } One returnl; A } - Private: - intNotgreaterthan (vector<int>& Nums,inttarget) { the intCNT =0; - for(intnum:nums) - if(Num <=target) -cnt++; + returnCNT; - } +};
[Leetcode] Find the Duplicate number