-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindDuplicate.cpp
More file actions
35 lines (33 loc) · 826 Bytes
/
findDuplicate.cpp
File metadata and controls
35 lines (33 loc) · 826 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
// Slow-Fast Pointers
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int slow = 0, fast = 0;
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while(slow != fast);
fast = 0;
while(slow != fast){
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
};
// Binary Search
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int left = 1, right = nums.size() - 1;
while (left < right) {
int mid = left + (right - left) / 2, cnt = 0;
for (int num : nums) {
if (num <= mid)
cnt += 1;
}
if (cnt > mid) right = mid;
else left = mid + 1;
}
return left;
}