位图法JAVA

来源:互联网 发布:淘宝兼职有没有真的 编辑:程序博客网 时间:2024/05/30 07:14

位图法
bit-map(位图)法基本原理是使用位数字来表示某些元素是否存在,如8位电话号码中查重复号码,它适用于海量数据的快速查找、判重、删除等。
具体而言,位图是一个N位长的串,我们可用int[] 来描述。
例如集合{5,8,1,12,6,2},那么首先开辟2个字节的空间,也就是16位,分别对应0-15这16个数。

位图缺点:
1、可读性差
2、位图存储的元素个数虽然比一般做法多,但是存储的元素大小受限于存储空间的大小。位图存储性质:存储的元素个数等于元素的最大值。比如, 1K 字节内存,能记录值大小上限为 8K 的元素。(元素值上限为 8K ,这个局限性很大!)比如,要存储值为 65535 的数,就必须要 65535/8=8K 字节的内存。要就导致了位图法根本不适合存 unsigned int 类型的数(大约需要 2^32/8=5 亿字节的内存)。
3、位图对有符号类型数据的存储,需要 2 位来表示一个有符号元素。这会让位图能存储的元素个数,元素值大小上限减半。 比如 8K 字节内存空间存储 short 类型数据只能存 8K*4=32K 个,元素值大小范围为 -32K~32K 。

16以下的数进行排序以及统计不同数字个数public class BitGraph {    final int BITS_PRE_WORD = 32;    final static int max = 16;    void setBit(int[] arr, int n)    {        arr[n/BITS_PRE_WORD] |= (1 << (n % BITS_PRE_WORD));    }    void clearBit(int[] arr, int n){}    int getBit(int[] arr, int n)    {        return (arr[n/BITS_PRE_WORD] & (1 << (n%BITS_PRE_WORD))) != 0 ? 1 : 0;    }    public static void main(String[] args) {        // TODO Auto-generated method stub        BitGraph bg = new BitGraph();        int[] datas = new int[]{1,13,14,15,7,8,9,13,1,13,14,15,7,8,9,13,2};        int[] arr = new int[max / 32 + 1];        for(int data : datas)        {            bg.setBit(arr, data);        }        int count = 0;        for(int i = 0; i < max;i++)        {            if(bg.getBit(arr, i) == 1)            {                System.out.println(i);                ++count;            }        }        System.out.println("count" +count);    }}
1 0
原创粉丝点击