存储空间的计算
1int为4个字节(byte)
1byte为8个 比特位(bit)
1kb = 1024 byte
1Mb = 1024 kb
1Gb = 1024Mb
1Tb = 1024Gb
位图
腾讯题:给40亿个不重复的无符号整型,没排过序。如何快速判断这个数存不存在?
如果内存允许,可以先进行排序,再用二分查找进行查找。但是40亿个无符号整型存储在内存中需要16G。
如果用位图40亿个整型需要内存为500M。
位图是一个数组的每一个数据的每一个二进制位表示一个数据,0表示数据不存在,1表示数据存在。
代码:
"BitSet.h"
#pragma once
#include <vector>
class BitSet
{
public:
BitSet(size_t range)//构造函数
{
_a.resize((range >> 5) + 1, 0);
}
void Set(size_t num)
{
size_t index = num >> 5;//在哪个数中
size_t pos = num % 32;//在哪个比特位中
_a[index] |= (1 << pos);//将num对应的位置1
}
void ReSet(size_t num)
{
size_t index = num >> 5;
size_t pos = num % 32;
_a[index] &= ~(1 << pos);//将num对应的位置0
}
bool Test(size_t num)//测试
{
size_t index = num >> 5;
size_t pos = num % 32;
return _a[index] & (1 << pos);//如果存在,对应的位是1,&1为1,否则相反
}
protected:
vector<int> _a;
};
void TestBitSet()
{
BitSet s1(-1);
s1.Set(1);
cout << "BitSet?:" << s1.Test(1) << endl;
s1.Set(33);
cout << "BitSet?:" << s1.Test(33) << endl;
s1.Set(67);
cout << "BitSet?:" << s1.Test(67) << endl;
s1.ReSet(1);
cout << "BitSet?:" << s1.Test(1) << endl;
s1.ReSet(33);
cout << "BitSet?:" << s1.Test(33) << endl;
s1.ReSet(67);
cout << "BitSet?:" << s1.Test(67) << endl;
}
"Test.cpp"
#include <iostream>
using namespace std;
#include "BitSet.h"
int main()
{
TestBitSet();
return 0;
}