我感觉自己对这个问题过于深思熟虑了,但还是来发一波...
我有一个哈希表,在它的内部数组中有M个插槽。 我需要将N个元素插入哈希表中。 假设我有一个哈希函数,以相同概率将元素随机插入到每个插槽中,那么哈希冲突的总数的期望值是多少?
(很抱歉这更像是一个数学问题而不是一个编程问题)。
编辑:
这里有一些我用Python模拟的代码。 我得到了数值答案,但是很难推广到公式并解释它。
import random
import pdb
N = 5
M = 8
NUM_ITER = 100000
def get_collisions(table):
col = 0
for item in table:
if item > 1:
col += (item-1)
return col
def run():
table = [0 for x in range(M)]
for i in range(N):
table[int(random.random() * M)] += 1
#print table
return get_collisions(table)
# Main
total = 0
for i in range(NUM_ITER):
total += run()
print float(total)/NUM_ITER
SUM(x * (x+1) /2)
,其中 X 是桶中项目的数量,总和是所有桶的总和。 - wildplasser