forked from moranzcw/LeetCode-NOTES
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.cpp
More file actions
33 lines (33 loc) · 854 Bytes
/
solution.cpp
File metadata and controls
33 lines (33 loc) · 854 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
class Solution
{
public:
int findDuplicate(vector<int>& nums)
{
int min = 0, max = nums.size() - 1;
while(min <= max)
{
// 找到中间那个数
int mid = min + (max - min) / 2;
int cnt = 0;
// 计算总数组中有多少个数小于等于中间数
for(int i = 0; i < nums.size(); i++)
{
if(nums[i] <= mid)
{
cnt++;
}
}
// 如果小于等于中间数的数量大于中间数,说明前半部分必有重复
if(cnt > mid)
{
max = mid - 1;
// 否则后半部分必有重复
}
else
{
min = mid + 1;
}
}
return min;
}
};