Created
October 7, 2022 19:41
-
-
Save webber2408/e1b5afd982a1f7d1e5a8b2a93132b73f to your computer and use it in GitHub Desktop.
Approach-4) Find Duplicates - Using Binary Search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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