-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindtheDuplicateNumber.cpp
More file actions
41 lines (39 loc) · 944 Bytes
/
Copy pathFindtheDuplicateNumber.cpp
File metadata and controls
41 lines (39 loc) · 944 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <vector>
using namespace std;
class Solution {
public:
/*Sol 0
* Just like Linked List Cycle II
* Find the cycle O(n)
*/
int findDuplicate(vector<int>& nums) {
int slow = 0,fast = 0;
while(true){
slow = nums[slow];
fast = nums[nums[fast]];
if(slow==fast) break;
}
fast = 0;
while(slow != fast){
fast = nums[fast];
slow = nums[slow];
}
return slow;
}
/* Sol 1
* Binary search O[n(logn)]
*/
int findDuplicate1(vector<int>& nums){
int left = 0,right = nums.size()-1;
while(left<right){
int middle = (left+right) / 2;
int count = 0;
for(auto num:nums){
if(num <= middle) ++count;
}
if(count>middle) right = middle;
else left = middle+1;
}
return left;
}
};