Post

线性探查法

线性探查法实现要点:

  1. 将问题简化为:keyvalue的类型均为int,且table.length = 10,hash函数的实现为hash(key) = key % 10
  2. 使用环形数组技巧:遍历到数组末尾时若仍然没有空位则需要转到数组首部继续寻找。
  3. 删除操作需谨慎!: 若直接置空则会影响元素连续性。 操作如下:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    add(0, a)
    add(10, b)
    add(20, c)
    
    add(3, A)
    add(13, B)
    
    add(30, d)
    add(40, e)
    

    则底层table数组应该像这样:

    1
    2
    3
    4
    
     table:[a, b, c, A, B, d, e, _, _, _]
     index: 0  1  2  3  4  5  6  7  8  9
     hash:  ^        ^
     key:   0  10 20 3  4  30 40
    

    若接下来你想删除key = 10这一键值对,不能直接将table[1]直接置为None,若置为None则会有如下结果: 底层table数组如下:

    1
    2
    3
    4
    
     table:[a, _, c, A, B, d, e, _, _, _]
     index: 0  1  2  3  4  5  6  7  8  9
     hash:  ^        ^
     key:   0     20 3  4  30 40
    

    这样元素就不连续了,若此时调用get(20), get(30), get(40)则会出错,找不到对应的key:当调用get(20)时,从table[0]开始线性探测,当探测到table[1]时返回结果是None,因此认为探测链已结束,结束探测。

  4. 删除具体操作:
    • 数据搬移
    • 使用占位符 而大部分编程语言标准库实现哈希表都使用的是拉链法,因为其可以实现无限大的负载因子。
This post is licensed under CC BY 4.0 by the author.