Find the Duplicate Number数组中重复的数
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: [1,3,4,2,2]
Output: 2
Example 2:
Input: [3,1,3,4,2]
Output: 3
Note:
You must not modify the array (assume the array is read only).
You must use only constant, O(1) extra space.
Your runtime complexity should be less than O(n2).
There is only one duplicate number in the array, but it could be repeated more than once.
题意:数组中有1+n个数都是1到n之间,找出其中重复的。
解法一:二分搜索,先求出中点mid,然后遍历整个数组,统计所有小于等于mid的数的个数,如果个数小于等于mid,则说明重复值在[mid+1, n]之间,反之,重复值应在[1, mid-1]之间。
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int left = 0, right = nums.size();
while(left < right){
int mid = left + (right - left) / 2;
int cnt = 0;
for(int num : nums){
if(num <= mid)
cnt++;
}
if(cnt <= mid) left = mid + 1;
else right = mid;
}
return right;
}
};
解法二:利用快慢指针,思路和带环链表那一题一样,因为数组中只有1到n之间的数,使得数组下标和值可以跳转,例如样例1中的[1 3 4 2 2]数组元素的跳转
最后肯定会碰到循环,此时利用之前带环链表求入口的思路就能求得开始循环的那个值,也就是重复的。
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int slow = 0, fast = 0, slow2 = 0;
while(true){
slow = nums[slow];
fast = nums[nums[fast]];
if(slow == fast){
while(slow != slow2){
slow = nums[slow];
slow2 = nums[slow2];
}
return slow;
}
}
}
};