题目描述
思路分析
方法1:二分
方法2:转化为环形链表这个题
代码实现
//方法1:二分。二分数的大小范围,取个数大于一半的一边继续二分。
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int l = 1, r = nums.size() - 1;
while (l < r) {
int mid = l + r >> 1; // 划分的区间:[l, mid], [mid + 1, r]
int s = 0;
for (auto x : nums) s += x >= l && x <= mid;
if (s > mid - l + 1) r = mid;
else l = mid + 1;
}
return r;
}
};
//方法2:建图,然后转化为环形链表找入口点
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int a=0,b=0;
while(1){
a=nums[a];
b=nums[nums[b]];
if(a==b){
a=0;
while(a!=b){
a=nums[a];
b=nums[b];
}
return a;
}
}
return -1;
}
};