位图
位图概念
-
面试题 给 40 亿个不重复的无符号整数,未排序。给定一个无符号整数,如何快速判断该数是否在这 40 亿个数中?【腾讯】
- 遍历:时间复杂度 O(N)
- 排序后二分查找:时间复杂度 O(logN)
-
位图概念 所谓位图,就是用每一位来存放某种状态,适用于海量数据且数据无重复的场景,通常用来判断某个数据是否存在。
位图解决思路 数据是否在给定的整形数据中,结果是在或者不在,刚好是两种状态,可以使用一个二进制比特位来代表数据是否存在的信息。如果二进制比特位为 1,代表存在;为 0 代表不存在。

位图的实现
namespace bit {
template<size_t N>
class bitset {
public:
bitset(size_t bitCount) : _bit((bitCount >> 5) + 1), _bitCount(bitCount) {}
// 将 which 比特位置 1
void set(size_t which) {
if (which > _bitCount) return;
size_t index = (which >> 5);
size_t pos = which % 32;
_bit[index] |= (1 << pos);
}
// 将 which 比特位置 0
void reset(size_t which) {
if (which > _bitCount) return;
size_t index = (which >> 5);
pos = which % ;
_bit[index] &= ~( << pos);
}
{
(which > _bitCount) ;
index = (which >> );
pos = which % ;
_bit[index] & ( << pos);
}
{ _bitCount; }
{
bitCntTable[] = {
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , , ,
, , , , , , , , , , , , , , ,
};
size = _bit.();
count = ;
( i = ; i < size; ++i) {
value = _bit[i];
j = ;
(j < (_bit[])) {
c = value;
count += bitCntTable[c];
++j;
value >>= ;
}
}
count;
}
:
vector<> _bit;
_bitCount;
};
{
bitset<100> bs1;
bs();
bs();
bs();
( i = ; i < ; i++) {
(bs(i)) {
cout << i << << << endl;
} {
cout << i << << << endl;
}
}
bs();
bs();
cout << endl << endl;
( i = ; i < ; i++) {
(bs(i)) {
cout << i << << << endl;
} {
cout << i << << << endl;
}
}
}
< N>
{
:
{
(_bs(x) == && _bs(x) == ) {
_bs(x);
} (_bs(x) == && _bs(x) == ) {
_bs(x);
_bs(x);
}
}
{
(_bs(x) == && _bs(x) == ) {
;
}
;
}
:
bitset<N> _bs1;
bitset<N> _bs2;
};
{
a[] = { , , , , , , , , , , , , , , , , };
two_bit_set<> bs;
( e : a) {
bs.(e);
}
( i = ; i < ; i++) {
(bs.(i)) {
cout << i << endl;
}
}
}
{
a1[] = { , , , , , , , , , , , , , , , , };
a2[] = { , , , , , , , };
bitset<100> bs1;
bitset<100> bs2;
( e : a1) {
bs(e);
}
( e : a2) {
bs(e);
}
( i = ; i < ; i++) {
(bs(i) && bs(i)) {
cout << i << endl;
}
}
}
}





