Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. Example 1: Input: Example 2: Input: [3,1,3,4,2] Output: 3 Note:
|
给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。 示例 1: 输入: 示例 2: 输入: [3,1,3,4,2] 输出: 3 说明:
|
思路:题目要求不能修改原数组,不能增加空间,时间小于O(n),但是题目给出数字都是1~n 之间。所以联想 到二分法。在这里二分法的思路是,mid=left+(right-left)/2;然后定义一个 统计<=mid的数字出现的次数。如果<=mid的数字出现的次数小于mid,那就说明重复元素在 大于mid的范围内,将right=mid+1;否则,说明重复元素在0~mid范围内,那就right=mid;
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int left=0,right=nums.size();
while(left<right)
{
int mid = left + (right-left)/2,count=0;
for(auto n:nums)
if(n<=mid) count++;
if(count<=mid) left=mid+1;
else right=mid;
}return right;
}
};