zoukankan      html  css  js  c++  java
  • 用Java写一个简单的Bitmap

    /**
     * Bitmap用于标识[low, high]区间内的数的占用情况,
     * 进一步可以用来去重,用来排序等
     */
    private static class Bitmap {
        // 区间的左边界,默认为0
        private int low;
        // 区间的右边界
        private int high;
    
        // bitmap
        private byte[] bitmap;
    
        public Bitmap(int high) {
            this(0, high);
        }
    
        public Bitmap(int low, int high) {
            this.low = low;
            this.high = high;
            bitmap = new byte[(high - low) / Byte.SIZE + 1];
        }
    
        /**
         * 将x加入到bitmap中
         *
         * @param x 将要加入bitmap的数字
         * @return 如果x不在[low, high]区间中,返回false,如果将x加入bitmap成功则返回true
         */
        public boolean add(int x) {
            if (x < low || x > high) return false;
            int bitIndex = x - low;
            int blockIndex = bitIndex / Byte.SIZE;
            int offset = bitIndex % Byte.SIZE;
            byte mask = (byte) (Byte.MIN_VALUE >>> offset);
            bitmap[blockIndex] |= mask;
            return true;
        }
    
        /**
         * 将x从bitmap中删除
         *
         * @param x 将要从bitmap中删除的数字
         * @return 如果x不在[low, high]区间中,返回false,如果将x从bitmap删除成功则返回true
         */
        public boolean remove(int x) {
            if (x < low || x > high) return false;
            int bitIndex = x - low;
            int blockIndex = bitIndex / Byte.SIZE;
            int offset = bitIndex % Byte.SIZE;
            byte mask = (byte) (Byte.MIN_VALUE >>> offset);
            bitmap[blockIndex] &= ~mask;
            return true;
        }
    
        /**
         * 判断bitmap中是否存在数字x
         *
         * @param x
         * @return 如果x不在[low, high]区间中或者bitmap中不存在x,返回false,如果bitmap中存在x则返回true
         */
        public boolean contains(int x) {
            if (x < low || x > high) return false;
            int bitIndex = x - low;
            int blockIndex = bitIndex / Byte.SIZE;
            int offset = bitIndex % Byte.SIZE;
            byte mask = (byte) (Byte.MIN_VALUE >>> offset);
            return (bitmap[blockIndex] & mask) != 0;
        }
    
        public int getLow() {
            return low;
        }
    
        public int getHigh() {
            return high;
        }
    
    }
    
    -------------------------------------
    吾生也有涯,而知也无涯。
  • 相关阅读:
    什么是 Visual VM?
    myeclipse svn 修改用户名和密码
    unix/linux共享内存应用与陷阱
    linux内存查看方式
    Linux下crontab命令的用法
    linux ftp命令参数全集
    XmlDataSource控件绑定GridView
    VC++发布Activex控件
    SqlServer数据库自定义Split()函数
    C和C++中的主要数据类型和字节大小
  • 原文地址:https://www.cnblogs.com/SanjiApollo/p/13301907.html
Copyright © 2011-2022 走看看