哈希查找(Hash Search)是一种基于哈希表的查找算法,它通过将关键字映射到不同的桶中进行查找。在哈希表中,每个桶对应一个链表或者红黑树等数据结构,用于存储具有相同哈希值的元素。
以下是 golang 实现哈希查找的示例代码:
type Node struct {
key int
value interface{}
next *Node
}
type HashTable struct {
size int // 哈希表大小
table []*Node // 哈希表数组
}
// 创建哈希表
func NewHashTable(size int) *HashTable {
return &HashTable{
size: size,
table: make([]*Node, size),
}
}
// 计算哈希值
func (ht *HashTable) hash(key int) int {
return key % ht.size
}
// 插入元素
func (ht *HashTable) Insert(key int, value interface{}) {
index := ht.hash(key)
node := &Node{
key: key,
value: value,
next: nil,
}
if ht.table[index] == nil { // 桶中没有元素,直接插入
ht.table[index] = node
return
}
// 桶中已经存在元素,使用链表法解决冲突(将新节点插入链表头部)
head := ht.table[index]
node.next = head
ht.table[index] = node
}
// 查找元素
func (ht *HashTable) Search(key int) interface{} {
index := ht.hash(key)
node := ht.table[index]
for node != nil {
if node.key == key {
return node.value
}
node = node.next
}
return nil
}
// 删除元素
func (ht *HashTable) Delete(key int) bool {
index := ht.hash(key)
head := ht.table[index]
if head == nil { // 桶中没有元素,直接返回 false
return false
}
if head.key == key { // 删除链表头部元素
ht.table[index] = head.next
return true
}
prev := head // 遍历链表查找待删除节点的前一个节点
for prev.next != nil && prev.next.key != key {
prev = prev.next
}
if prev.next == nil { // 没有找到对应的节点,返回 false
return false
}
prev.next = prev.next.next // 删除待删除节点
return true
}
在该代码中,我们使用了哈希表来实现哈希查找。具体步骤如下:
创建哈希表:初始化大小为 size 的数组 table。
计算哈希值:将关键字通过某种哈希函数计算出对应的桶位置 index。
插入元素:将新的键值对插入到 table[index] 对应的链表头部。
查找元素:从 table[index] 对应的链表头开始遍历,查找是否存在对应的键值对。
删除元素:查找待删除节点的前一个节点 prev,将 prev.next 指向待删除节点的下一个节点。
时间复杂度:哈希表的查找、插入和删除操作时间复杂度均为 \(O(1)\),但需要考虑哈希函数的性能和哈希冲突的处理。
空间复杂度:\(O(n)\)
稳定性:不稳定




