Skip to content

Instantly share code, notes, and snippets.

@webber2408
Created October 7, 2022 19:41
Show Gist options
  • Save webber2408/e1b5afd982a1f7d1e5a8b2a93132b73f to your computer and use it in GitHub Desktop.
Save webber2408/e1b5afd982a1f7d1e5a8b2a93132b73f to your computer and use it in GitHub Desktop.
Approach-4) Find Duplicates - Using Binary Search
class Solution {
public:
int findDuplicate(vector<int>& nums) {
// Lambda function to count how many numbers are less than or equal to 'cur'
auto small_or_equal = [&](int cur) {
int count = 0;
for (auto &num: nums) {
if (num <= cur)
count++;
}
return count;
};
// 'low' and 'high' represent the range of values of the target
int low = 1, high = nums.size();
int duplicate = -1;
while (low <= high) {
int cur = (low + high) / 2;
if (small_or_equal(cur) > cur) {
duplicate = cur;
high = cur - 1;
} else {
low = cur + 1;
}
}
return duplicate;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment