布隆过滤器
如果要经常判断 1 个元素是否存在,你会怎么做?很容易想到使用哈希表(HashSet、HashMap),将元素作为 key 去查找,时间复杂度:O(1),但是空间利用率不高,需要占用比较多的内存资源。
如果需要编写一个网络爬虫去爬10亿个网站数据,为了避免爬到重复的网站,如何判断某个网站是否爬过?很显然,HashSet、HashMap 并不是非常好的选择是否存在时间复杂度低、占用内存较少的方案?布隆过滤器(Bloom Filter)。
1、布隆过滤器:
1970年由布隆提出,它是一个空间效率高的概率型数据结构,可以用来告诉你:一个元素一定不存在或者可能存在。它实质上是一个很长的二进制向量和一系列随机映射函数(Hash函数)
优缺点
优点:空间效率和查询时间都远远超过一般的算法
缺点:有一定的误判率、删除困难
常见应用
网页黑名单系统、垃圾邮件过滤系统、爬虫的网址判重系统、解决缓存穿透问题
2、原理:
3、代码:
package com.mj; public class BloomFilter<T> { /** * 二进制向量的长度(一共有多少个二进制位) */ private int bitSize; /** * 二进制向量 */ private long[] bits; /** * 哈希函数的个数 */ private int hashSize; /** * @param n 数据规模 * @param p 误判率, 取值范围(0, 1) */ public BloomFilter(int n, double p) { if (n <= 0 || p <= 0 || p >= 1) { throw new IllegalArgumentException("wrong n or p"); } double ln2 = Math.log(2); // 求出二进制向量的长度 bitSize = (int) (- (n * Math.log(p)) / (ln2 * ln2)); // 求出哈希函数的个数 hashSize = (int) (bitSize * ln2 / n); // bits数组的长度 bits = new long[(bitSize + Long.SIZE - 1) / Long.SIZE]; // 每一页显示100条数据, pageSize // 一共有999999条数据, n // 请问有多少页 pageCount = (n + pageSize - 1) / pageSize } /** * 添加元素1 */ public boolean put(T value) { nullCheck(value); // 利用value生成2个整数 int hash1 = value.hashCode(); int hash2 = hash1 >>> 16; boolean result = false; for (int i = 1; i <= hashSize; i++) { int combinedHash = hash1 + (i * hash2); if (combinedHash < 0) { combinedHash = ~combinedHash; } // 生成一个二进位的索引 int index = combinedHash % bitSize; // 设置index位置的二进位为1 if (set(index)) result = true; // 101010101010010101 // | 000000000000000100 1 << index // 101010111010010101 } return result; } /** * 判断一个元素是否存在 */ public boolean contains(T value) { nullCheck(value); // 利用value生成2个整数 int hash1 = value.hashCode(); int hash2 = hash1 >>> 16; for (int i = 1; i <= hashSize; i++) { int combinedHash = hash1 + (i * hash2); if (combinedHash < 0) { combinedHash = ~combinedHash; } // 生成一个二进位的索引 int index = combinedHash % bitSize; // 查询index位置的二进位是否为0 if (!get(index)) return false; } return true; } /** * 设置index位置的二进位为1 */ private boolean set(int index) { long value = bits[index / Long.SIZE]; int bitValue = 1 << (index % Long.SIZE); bits[index / Long.SIZE] = value | bitValue; return (value & bitValue) == 0; } /** * 查看index位置的二进位的值 * @return true代表1, false代表0 */ private boolean get(int index) { long value = bits[index / Long.SIZE]; return (value & (1 << (index % Long.SIZE))) != 0; } private void nullCheck(T value) { if (value == null) { throw new IllegalArgumentException("Value must not be null."); } } }
。。。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)