🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
- 开放地址法(Open Addressing)**:在哈希表中的每个槽位中存储一个单独的键值对,当发生哈希冲突时,根据某种策略(如线性探测、二次探测、双重哈希等)在哈希表中寻找下一个可用的槽位 ~~~ package main import ( "fmt" ) const tableSize = 10 type HashTable struct { keys []int values []string } func NewHashTable() *HashTable { return &HashTable{ keys: make([]int, tableSize), values: make([]string, tableSize), } } func (ht *HashTable) hash(key int) int { return key % tableSize } func (ht *HashTable) insert(key int, value string) { index := ht.hash(key) for ht.keys[index] != 0 { index = (index + 1) % tableSize } ht.keys[index] = key ht.values[index] = value } func (ht *HashTable) search(key int) (string, bool) { index := ht.hash(key) for ht.keys[index] != 0 { if ht.keys[index] == key { return ht.values[index], true } index = (index + 1) % tableSize } return "", false } func main() { hashTable := NewHashTable() hashTable.insert(5, "Apple") hashTable.insert(15, "Banana") hashTable.insert(25, "Orange") // Search for values if value, found := hashTable.search(5); found { fmt.Println("Key 5 found, value:", value) } else { fmt.Println("Key 5 not found") } if value, found := hashTable.search(15); found { fmt.Println("Key 15 found, value:", value) } else { fmt.Println("Key 15 not found") } if value, found := hashTable.search(25); found { fmt.Println("Key 25 found, value:", value) } else { fmt.Println("Key 25 not found") } if _, found := hashTable.search(35); !found { fmt.Println("Key 35 not found") } } ~~~