给两个文件,分别有100亿个字符串,我们只要1g的内存,如何找到两个文件的交集?分别给出精确算法和近似算法?
精确算法:
我们可以创建1000个文件,运用哈希函数先将文件1的字符串保存在对应的文件中,之后再文件2中取元素,通过哈希函数计算出哈希地址,去对应的文件里面找是否有与之相同的字符串。
近似算法:
我们可以使用位图的方法,通过一个函数将一个元素映射成一个位矩阵中的一个点,这样一来,我们只要看看这个点是不是1就知道集合里有没有它了。 但是有可能两个字符串对应的整数是一样的,对于这种情况我们可以设置更多的哈希函数,对应更多的地址,这样更加精确。
位图相关问题
代码实现:
BloomFilter.h
#include"BitMap.h"
//定义一个函数指针、函数返回类型为int、参数为字符串
typedef int(*STRTOINT)(const char *);
typedef struct BloomFilter{
BitMap _bmp;
int size;
STRTOINT HashFun[5];
}BloomFilter;
//初始化
void InitBloomFilter(BloomFilter *BloomFilter, int total, STRTOINT *hashfun);
//插入
void InsertBloomFilter(BloomFilter *BloomFilter, char *str);
//大小
int SizeBloomFilter(BloomFilter *BloomFilter);
//查询
int FindBloomFilter(BloomFilter* BloomFilter, char *str);
//删除
void DeleteBloomFilter(BloomFilter *BloomFilter, char *str);
///////////////////////////////////////////////////////////////////////////
//5种字符串转整形的方法
int HashFun1(const char *str)
{
unsigned int hash = 0;
while (*str)
{
// equivalent to: hash = 65599*hash + (*str++);
hash = (*str++) + (hash << 6) + (hash << 16) - hash;
}
return (hash & 0x7FFFFFFF);
}
// RS Hash Function
int HashFun2(const char *str)
{
unsigned int b = 378551;
unsigned int a = 63689;
unsigned int hash = 0;
while (*str)
{
hash = hash * a + (*str++);
a *= b;
}
return (hash & 0x7FFFFFFF);
}
// JS Hash Function
int HashFun3(const char *str)
{
unsigned int hash = 1315423911;
while (*str)
{
hash ^= ((hash << 5) + (*str++) + (hash >> 2));
}
return (hash & 0x7FFFFFFF);
}
// P. J. Weinberger Hash Function
int HashFun4(const char *str)
{
unsigned int BitsInUnignedInt = (unsigned int)(sizeof(unsigned int)* 8