<笔试><面试>判断一个数是否在40亿个中
2016-05-12 20:39
561 查看
40亿个不重复无符号整数,没排序,任意给一个无符号整数如何快速判断这个数是否在这40亿个数中。
思路:
(位图BitMap) 在STL中叫bit_set 节省空间;缺点只判定存在还是不存在,不能知道出现几次。
思路:
(位图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; }
相关文章推荐
- 计算WWW在线人数
- 文件遍历排序函数
- sql server字符串非空判断实现方法
- C# 判断字符为空的6种方法的效率实测对比
- C#中实现判断某个类是否实现了某个接口
- C#判断多个文本框是否为空的方法
- C#实现判断一个时间点是否位于给定时间区间的方法
- C#实现判断操作系统是否为Win8以上版本
- 使用dos批处理文件的几个高级命令,判断
- 一个域名查询的程序
- 网站当前的在线人数
- 一个简洁的多级别论坛
- 一个目录遍历函数
- PHP判断IP并转跳到相应城市分站的方法
- CMS中PHP判断系统是否已经安装的方法示例
- C#判断一个图像是否是透明的GIF图的方法
- C#判断指定驱动器是否已经准备就绪的方法
- C#判断给定IP地址是否在指定范围内的方法
- C#判断某程序是否运行的方法