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.
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.
题意:给定一个包含n + 1个整数(其中每个整数介于1和n(含)之间)的数组nums,证明至少存在一个重复数。 假设只有一个重复数,找到重复数。
注意:
- 不能修改队列
- 固定O(1)额外空间
- 时间复杂度少于O(n^2)
只有一个重复数,但可能出现不止一次
Approach One: Sort
int findDuplicate(vector<int>& nums) {
std::sort(nums.begin(), nums.end());
for(int i = 1; i < nums.size(); ++i)
if(nums[i - 1] == nums[i])
return nums[i];
return -1;
}
Approach Two: Use Set
int findDuplicate(vector<int>& nums) {
unordered_set<int> set;
for(int i = 0; i < nums.size(); ++i)
if(set.count(nums[i]) == 0)
set.emplace(nums[i]);
else
return nums[i];
return -1;
}
Approach There: Cycle Detection
我们可以把整个数组看成一个链表,寻找环,可以参考Linked List Cycle II:
https://blog.csdn.net/spade_/article/details/79593290
int findDuplicate(vector<int>& nums) {
int slow = nums[0], fast = nums[0];
do{
slow = nums[slow];
fast = nums[nums[fast]];
}while(slow != fast);
slow = nums[0];
while(slow != fast){
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
Approach Four: Bit Manipulation
/*
看了讨论,发现了Bit Manipulation的解决方法:
对于 int 32 位,统计nums[0..n-1]在第k位的1的总数b,与0..n-1在第k位的1的总数a
如果b > a,说明第k位存在重复(多了1)
*/
int findDuplicate(vector<int>& nums) {
int res = 0;
for(int k = 0; k < 32; ++k){
int bit = (1 << k); // 1 右移 k 位
int a = 0, b = 0;
for(int i = 0; i < nums.size(); ++i){
if((i & bit) > 0) ++a;
if((nums[i] & bit) > 0) ++b;
}
if(b > a) res += bit; // 重复数的k位
}
return res;
}