lurenaa的博客

😂二分法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int findDuplicate(vector<int>& nums) {
sort(nums.begin(), nums.end());
find(nums, 0, nums.size() - 1);
return answer;
}
void find(vector<int>& nums, int left, int right) {
if(left > right)
return ;
int mid = (left + right ) / 2;
if(mid - 1 >= 0 && nums[mid - 1] == nums[mid] || mid + 1 <= nums.size() - 1 && nums[mid + 1] == nums[mid])
answer = nums[mid];
find(nums, left, mid - 1);
find(nums, mid + 1, right);
}
private:
int answer;
};

Accepted

53/53 cases passed (20 ms)

Your runtime beats 23 % of cpp submissions

Your memory usage beats 5.07 % of cpp submissions (13.4 MB)