出自 LeetCode 287,
给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。
示例 1:
输入: [1,3,4,2,2]
输出: 2
示例 2:
输入: [3,1,3,4,2]
输出: 3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-the-duplicate-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我想到一种和标准答案思路不同,且符合 题目要求的方法,即 O(n)时间, O(1)空间的方法, 统计位的出现频率即可, 如果某个位上 1 的数量超过了 1-n中这个位上1的所有出现次数,那么说明重复的数在这个位上为1
全部代码如下:
#include "haithink_common.h"
int findDuplicate(vector<int>& nums) {
const int INT_SIZE = sizeof(int)*8;
int len = nums.size();
int res = 0;
for (int i = 0; i < INT_SIZE; i++) {
int cnt = 0;
int x;
x = 1 << i;
for (int j = 1; j < len; j++) {
if (j & x) {
cnt++;
}
}
int cnt2 = 0;
for (int j = 0; j < len; j++) {
if (nums[j] & x) {
cnt2++;
}
}
if (cnt2 > cnt) {
res |= x;
}
}
return res;
}
int main()
{
vector<int> nums = { 14,16,12,1,16,17,6,8,5,19,16,13,16,3,11,16,4,16,9,7 };
//std::sort(nums.begin(), nums.end());
output(nums);
output(findDuplicate(nums));
return 0;
}