版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/renchunlin66/article/details/51375377
(一)设计思路
2.给40亿个不重复的无符号整数,没排过序。给一个无符号整数,如何快速判断一个数是否在这40亿个数中。 【腾讯】
思路:如果内存够的话,40亿个整型使用位图存储需要500M左右的空间。
位图实际上就是数组,这个数组中的每个数据的每个二进制位表示一个数的存在与否,存在的话二进制位位1,否则为0.
#pragma once
#include <vector>
class BitMap
{
public:
BitMap()
:_size(0)
{}
BitMap(size_t size)//这里size_t是4个字节,共32位,所以一个size可以表示32个数的状态
:_size(0)
{
_arrays.resize((size >> 5) + 1);//由于当size小于8的时候,右移5位后可能是0,因此加上1,保证最少开辟1个字节
}
bool Set(size_t num)
{
size_t index = num >> 5;//相当于除以32,找到它是第几个数,即index
size_t n = num % 32;//%32找到num在位图的第index个数上的第n位
if (_arrays[index] & (1 << n))//由于调用一次Set,_size就会加一,这样_size就不准了。
//这样写就避免这个问题了
{
return false;
}
_arrays[index] |= (1 << n);
++_size;
return true;
}
bool ReSet(size_t num)
{
size_t index = num >> 5;
size_t n = num % 32;
if (_arrays[index] & (1 << n))//原先这个位是1,现在改成0,当然_size也要减一
{
_arrays[index] &= (~(1 << n));
--_size;
return true;
}
else
{
return false;
}
}
bool Test(size_t num)
{
size_t index = num >> 5;
size_t n = num % 32;
return _arrays[index] & (1 << n);
}
void Clear()//置空该位图
{
_arrays.assign(_arrays.size(), 0);
}
protected:
vector<size_t> _arrays;
size_t _size;
};
void Test1()
{
BitMap bm(65);
bm.Set(1);
bm.Set(4);
bm.Set(33);
cout << "1?" << bm.Test(1) << endl;
cout << "2?" << bm.Test(2) << endl;
cout << "4?" << bm.Test(4) << endl;
cout << "33?" << bm.Test(33) << endl;
bm.ReSet(33);
bm.ReSet(4);
cout << "1?" << bm.Test(1) << endl;
cout << "2?" << bm.Test(2) << endl;
cout << "4?" << bm.Test(4) << endl;
cout << "33?" << bm.Test(33) << endl;
}
void Test2()
{
BitMap bm(-1);
bm.Set(10000000);
}