题目描述:
给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-the-duplicate-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
运行结果:
代码描述:
class Solution {
public:
int findDuplicate(vector<int>& nums) {
char *bytes;
size_t nbit = nums.size();
bytes = new char[nbit/8 + 1]();
vector<int>::iterator it = nums.begin();
size_t byteIndex;
size_t bitIndex;
for(; it != nums.end(); ++it)
{
byteIndex = *it/8;
bitIndex = *it%8;
if((bytes[byteIndex] & (1 << bitIndex)))
break;
else
bytes[byteIndex] |= (1<<bitIndex);
}
delete []bytes;
return *it;
}
};
理论上来讲,实际的时间复杂度小于O(n)
使用 bitmap 来解题,实际的空间复杂度为O(n/8)。
关于 bitmap 算法 的应用,参考链接: