mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
36 lines
1.5 KiB
Markdown
36 lines
1.5 KiB
Markdown
![]() |
# [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;
|
|||
|
}
|
|||
|
};
|
|||
|
```
|