算法入门——散列表 python实现

该内容来自《算法图解》一书,只是对书的内容做一些记录。

我们使用散列函数将给定键转化为一个“数组的索引”,理想情况下,不同的key会被转为不同的索引。

关键码和存储位置之间的对应函数是散列函数,也称为哈希函数,hash函数。

散列表查找时间为O(1)

python创建散列表两种方式:

phone_book=dict()#字典
phone_book={}

应用:

  • 查找
  • 防止重复

如防止投票重复

voted={}#创建字典,散列表
def check_voter(name):
    if voted.get(name):#name如果存在字典中
        print("kick them out!")
    else:
        voted[name]=True
        print("let them vote!")
check_voter("tom")  ==》let them vote!
check_voter("mike")  ==》let them vote!
check_voter("mike")  ==》kick them out!
  • 用作网页缓存

冲突

处理冲突的方法:https://blog.csdn.net/qq_22238021/article/details/78258605

散列表避免冲突需要有:

  • 较低的填装因子==》总数/长度 一般大于0.7就要对散列表长度进行调整
  • 良好的散列函数

猜你喜欢

转载自blog.csdn.net/qq_33266320/article/details/84927651