<笔试><面试>判断一个数是否在40亿个中
2016-06-05 10:59
696 查看
40亿个不重复无符号整数,没排序,任意给一个无符号整数如何快速判断这个数是否在这40亿个数中。
思路:
(位图BitMap) 在STL中叫bit_set 节省空间;缺点只判定存在还是不存在,不能知道出现几次。
![](http://s2.51cto.com/wyfs02/M01/80/04/wKioL1c0eZXh6XiwAAAukqJPQXQ338.png)
![](http://s4.51cto.com/wyfs02/M02/80/04/wKioL1c0d92iu_D8AADGqyH0-Q4224.jpg)
思路:
(位图BitMap) 在STL中叫bit_set 节省空间;缺点只判定存在还是不存在,不能知道出现几次。
![](http://s2.51cto.com/wyfs02/M01/80/04/wKioL1c0eZXh6XiwAAAukqJPQXQ338.png)
#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; }
![](http://s4.51cto.com/wyfs02/M02/80/04/wKioL1c0d92iu_D8AADGqyH0-Q4224.jpg)
相关文章推荐
- 笔试面试成对出现的一组数,只有一个或两个只出现一次的数字,找到它们。
- <笔试><面试>编写一个排序函数,实现,既可以排序整形数组,又可以排序字符串。
- <笔试><面试>单链表相关(1)从尾到头打印链表、删除一个无头链表的非尾结点
- 笔试面试单链表相关(2)在任意位置前插入结点、逆置链表
- 笔试面试,单链表相关(3)遍历一次找中间结点、倒数第K个结点
- 机器学习算法知识梳理--面试
- Java程序员必须掌握的排序算法Java实现整合一 :插入排序
- 面试算法总结
- iOS面试问题汇总
- 黑马程序员——Java基础---面向对象(构造方法和static关键字)
- 一道面试题中涉及到的SQL的高级使用
- 记我的一次电话面试 (转)
- 剑指Offer----面试题21:包含min函数的栈
- 展望未来,总结过去10年的程序员生涯,给程序员小弟弟小妹妹们的一些总结性忠告
- android常见面试题与回答 (二)
- java里的值传递和引用类型传递的经典面试题
- 一个工作一年半的程序员的自述(四)
- 面试题:从给定的N个正数中选取若干个数之和最接近M
- 面试题1:类的赋值运算符函数
- 赢在职场-WEB全栈开发-1-9 文本样式概览