Chinaunix首页 | 论坛 | 博客
  • 博客访问: 260359
  • 博文数量: 84
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 927
  • 用 户 组: 普通用户
  • 注册时间: 2015-03-06 23:00
个人简介

growing

文章分类

全部博文(84)

文章存档

2017年(6)

2016年(61)

2015年(17)

我的朋友

分类: C/C++

2016-04-03 13:09:32

应用场景:
【腾讯】
给40亿个不重复的无符号整数,没排过序。给一个无符号整数,如何快速判断一个数是否在这40亿个数中。 【腾讯】
思路:如果内存够的话,40亿个整型使用位图存储需要500M左右的空间。

代码:

  1. #pragma once
  2. #include <vector>

  3. class BitMap
  4. {
  5. public:
  6.     BitMap()
  7.         :_size(0)
  8.     {}
  9.     BitMap(size_t n)
  10.         :_size(0)
  11.     {
  12.         _array.resize((n>>5) + 1);
  13.     }
  14.     bool Test(size_t num)//查看此数是否存在
  15.     {
  16.         size_t index = num>>5;
  17.         size_t n = num % 32;

  18.         return _array[index]&(1<<n);
  19.     }
  20.     bool Set(size_t num)
  21.     {
  22.         size_t index = num>>5;
  23.         size_t n = num % 32;
  24.         if(_array[index] & (1<<n))//这个数已经存在了
  25.         {
  26.             return false;
  27.         }
  28.         _array[index] |= 1<<n;//注意这里,右移时是向其高位移动,并不是真的向右移动。
  29.         _size++;
  30.         return true;
  31.     }
  32.     bool Reset(size_t num)
  33.     {
  34.         size_t index = num>>5;
  35.         size_t n = num % 32;
  36.         if(!_array[index] & (1<<n))//这个数不存在
  37.         {
  38.             return false;
  39.         }
  40.         _array[index] &= ~(1<<n);
  41.         _size--;
  42.         return true;
  43.     }

  44.     void Clear()
  45.     {
  46.         _array.assign(_array.size(),0);
  47.     }
  48. protected:
  49.     vector<size_t> _array;
  50.     size_t _size;
  51. };
测试:

  1. #include <iostream>
  2. using namespace std;
  3. #include "BitSet.h"

  4. void test()
  5. {
  6.     BitMap bm1(100);
  7.     bm1.Set(1);
  8.     bm1.Set(33);
  9.     bm1.Set(69);
  10.     bm1.Set(100);

  11.     bm1.Reset(33);
  12. }
  13. int main()
  14. {
  15.     test();
  16.     return 0;
  17. }
注:给四十亿个数时,可以用BitMap(-1).
阅读(902) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~