您的位置:首页 > 职场人生

<笔试><面试>判断一个数是否在40亿个中

2016-05-12 20:39 561 查看
40亿个不重复无符号整数,没排序,任意给一个无符号整数如何快速判断这个数是否在这40亿个数中。
思路:
(位图BitMap) 在STL中叫bit_set 节省空间;缺点只判定存在还是不存在,不能知道出现几次。




#pragma once

#include<iostream>
using namespace std;
#include<vector>

class BitMap
{
public:
BitMap(size_t size)//size表示位的个数
:_size(0)
{
_a.resize((size>>5) + 1);//+1是为防止不能整除有余数
}

void Set(size_t x)//x对应位置1
{
size_t index = x >> 5;  //取到x在第index个size_t中
size_t num = x % 32;  //取到x在第index个size_t中的第num位
if (!(_a[index] & (1 << num)))
{
++_size;
}
_a[index] |= 1 << num;   //对应位置1
//cout << "_a[index] "<<_a[index]<< endl;
}

void Reset(size_t size)  //清空size对应的位
{
size_t index = size >> 5;
size_t num = size % 32;
_a[index] &= ~(1 << num);
_size--;
//cout << "_a[index] " << _a[index] << endl;

}

bool Test(size_t size)//检测size是否存在,也就是检测size对应位是否为1
{
size_t index = size >> 5;
size_t num = size % 32;
if (_a[index] & (1 << num))
{
return true;
}
return false;
}

protected:
vector<size_t> _a;
size_t _size;//表示表中元素个数
};

void test()
{
BitMap bm(40);
bm.Set(34);
bm.Set(35);
bm.Set(36);
bm.Set(37);
bm.Set(38);
cout << "34 is emist?  " << bm.Test(34) << endl;
cout << "35 is emist?  " << bm.Test(34) << endl;
cout << "36 is emist?  " << bm.Test(34) << endl;
cout << "37 is emist?  " << bm.Test(34) << endl;
cout << "38 is emist?  " << bm.Test(34) << endl;
bm.Reset(36);
bm.Reset(38);
cout << endl;
cout << "34 is emist?  " << bm.Test(34) << endl;
cout << "35 is emist?  " << bm.Test(35) << endl;
cout << "36 is emist?  " << bm.Test(36) << endl;
cout << "37 is emist?  " << bm.Test(37) << endl;
cout << "38 is emist?  " << bm.Test(38) << endl;

}

int main()
{
test();
system("pause");
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  判断 一个