BitSet位图

存储空间的计算

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值