287. Find the Duplicate Number
Input: [1,3,4,2,2]
Output: 2Input: [3,1,3,4,2]
Output: 3// Binary Search
int findDuplicate(vector<int>& nums) { // time: O(nlogn); space: O(1)
int low = 1, high = nums.size() - 1;
while (low < high) {
int mid = low + (high - low) / 2, cnt = 0;
for (int num : nums)
if (num <= mid) ++cnt;
if (cnt <= mid) low = mid + 1;
else high = mid;
}
return low;
}Last updated