Leetcode刷题笔记-287.寻找重复数
读题:n+1个数组,数字在[1,n]内,只存在一个重复的整数,但可能不止重复出现一次。
链接: https://leetcode-cn.com/problems/find-the-duplicate-number/.
条件:不能更改原数组,只能使用额外的 O(1) 的空间,时间复杂度小于 O(n2) 。
思路:二分法(可以用于确定一个有范围的整数)
回顾一下二分查找法:
int search(int a[],int e){
int low=0,high=L.length-1,mid;
while(low<=high){
mid=(low+high)/2;
if(a[mid]==e) return mid;
else if(a[mid]>e) high=mid-1;
else low=mid+1;
}
return -1;
}
二分法的思路是先猜一个数(有效范围 [left, right]里的中间数 mid),然后统计原始数组中小于等于这个中间数的元素的个数 num,如果 num 严格大于 mid,根据抽屉原理,重复元素就在区间 [left, mid] 里;
【补充抽屉原理】:桌上有十个苹果,要把这十个苹果放到九个抽屉里,无论怎样放,我们会发现至少会有一个抽屉里面放不少于两个苹果。
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int length=nums.size();
int left=1;
int right=length-1;
while(left<right){
int mid=(left+right)/2;
int count=0; //记录小于等于mid的个数
for(int num:nums)
{
if(num<=mid)
{
count++;
}
}
if(count>mid)
{
right=mid;
}
else{
left=mid+1;
}
}
return left;
}
};
作者:liweiwei1419
链接: https://leetcode-cn.com/problems/find-the-duplicate-number/solution/er-fen-fa-si-lu-ji-dai-ma-python-by-liweiwei1419/.