Files
kaka111222333-kaka111222333…/_posts/2014-10-09-bitmap.md
2019-11-17 01:12:14 +08:00

64 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
layout: post
title: Bitmap
tags: 算法 algorithm Bitmap
categories: algorithm
---
# bitmap
所谓bitmap就是用一个bit位来标记某个元素对应的value而key即是这个元素。由于采用bit为单位来存储数据因此在可以大大的节省存储空间
## 算法思想
32位机器上一个整形比如 `int a;` 在内存中占32bit可以用对应的32个bit位来表示十进制的0-31个数bitmap算法利用这种思想处理大量数据的排序与查询
优点:
* 效率高,不许进行比较和移位
* 占用内存少比如有N=10000000个正整数用bit存储占用内存为N/8 = 1250000Bytes = 1.2M如果采用int数组存储则需要38M以上
缺点:
无法对存在重复的数据进行排序和查找因为key唯一value只有0/1
示例:
申请一个int型的内存空间则有4Byte32bit。输入 4 2, 1, 3时
![bitmap][bitmap]
思想比较简单关键是十进制和二进制bit位需要一个map映射表把10进制映射到bit位上
## map映射表
假设需要排序或者查找的总数N=10000000那么我们需要申请的内存空间为 int a[N/32 + 1]。其中a[0]在内存中占32位,依此类推:
bitmap表为
a[0] ------> 0 - 31
a[1] ------> 32 - 63
a[2] ------> 64 - 95
a[3] ------> 96 - 127
......
## 位移转换
1 求十进制数0-N对应的在数组a中的下标
`index_loc = N / 32`即可index_loc即为n对应的数组下标。例如n = 76, 则loc = 76 / 32 = 2,因此76在a[2]中。
2求十进制数0-N对应的bit位
`bit_loc = N % 32`即可,例如 n = 76, bit_loc = 76 % 32 = 12
3利用移位0-31使得对应的32bit位为1
`int[index_loc] << bit_loc`
[bitmap]: {{"/bitmap.jpg" | prepend: site.imgrepo }}