假设我有一个非常大的数据集,无法放入内存,数据集中有数百万条记录,我想删除重复的行(实际上是保留重复行中的一行)
就空间和时间复杂度而言,最有效的方法是什么?
我的想法:
1.使用布隆过滤器,我不确定它是如何实现的,但我猜副作用是有误报,在那种情况下我们如何才能确定它是否真的是重复的?
2.使用散列值,在这种情况下,如果我们有少量重复值,唯一散列值的数量会很大,我们可能再次遇到内存问题,
最佳答案
您的解决方案 2:使用哈希值不会强制出现内存问题。您只需将散列空间划分为适合内存的片。更准确地说:
考虑一个存储记录集的哈希表,每条记录仅由其在表中的索引表示。例如,这样的哈希表将是 4GB。然后你把你的散列空间分成 k=4 片。根据散列值的最后两位数字,每条记录进入一个切片。所以算法大致如下:
let k = 2^M
for i from 0 to k-1:
t = new table
for each record r on the disk:
h = hashvalue(r)
if (the M last bit of h == i) {
insert r into t with respect to hash value h >> M
}
search t for duplicate and remove them
delete t from memory
缺点是您必须对每条记录进行 k 次哈希处理。优点是可以轻松分发。
这是 Python 中的原型(prototype):
# Fake huge database on the disks
records = ["askdjlsd", "kalsjdld", "alkjdslad", "askdjlsd"]*100
M = 2
mask = 2**(M+1)-1
class HashLink(object):
def __init__(self, idx):
self._idx = idx
self._hash = hash(records[idx]) # file access
def __hash__(self):
return self._hash >> M
# hashlink are equal if they link to equal objects
def __eq__(self, other):
return records[self._idx] == records[other._idx] # file access
def __repr__(self):
return str(records[self._idx])
to_be_deleted = list()
for i in range(2**M):
t = set()
for idx, rec in enumerate(records):
h = hash(rec)
if (h & mask == i):
if HashLink(idx) in t:
to_be_deleted.append(idx)
else:
t.add(HashLink(idx))
结果是:
>>> [records[idx] for idx in range(len(records)) if idx not in to_be_deleted]
['askdjlsd', 'kalsjdld', 'alkjdslad']
关于hash - 从大型数据集中删除重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17887769/