LeetCode/solutions/287. Find the Duplicate Number.md
2019-11-06 21:31:10 +08:00

36 lines
1.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [287. Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)
# 思路
给定一个长度为n+1的数组里面所有的元素都位于[1, n],所以很明显有重复元素,题目假设只有一个重复数字(但可以重复多次),求这个重复数字。要求空间复杂度为常数
且时间复杂度小于O(n^2)。
## 思路一
由于要求常数空间复杂度所以就不能用hash什么的然后要求时间复杂度小于O(n^2),暴力计数也不行。既然直接计数不行,那么我们可以考虑位操作:
计算32位中每一位当中1出现的次数。具体来讲对于第i位0 <= i <= 31我们用count1代表整个nums数组中所有元素第i位是1的个数
用count2代表0~n这些数中第i位是1的个数。若 count1 > count2说明最终所求的重复元素在第i位是1否则是0。这样我们就可以通过分别计算32位1出现的次数来得到结果。
时间复杂度为O(n)
# C++
## 思路一
``` C++
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int res = 0, mask = 1, n = nums.size() - 1;
for(int i = 0; i < 32; i++){
int count1 = 0, count2 = 0;
for(int j = 0; j <= n; j++){
if(mask & nums[j]) count1++;
if(mask & j) count2++;
}
if(count1 > count2) res += mask;
if(i < 31) mask <<= 1;
}
return res;
}
};
```