diff --git a/README.md b/README.md index 44c5060..f1f9574 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ - [590.N 叉树的后序遍历](leetcode/easy/590.go) - [653.两数之和 IV-输入 BST](leetcode/easy/653.go) - [705.设计哈希集合](leetcode/easy/t705/solution.go) +- [706.设计哈希映射](leetcode/easy/t706/solution.go) - [717.1 比特与 2 比特字符](leetcode/easy/717.go) - [748.最短补全词](leetcode/easy/748.go) - [762.二进制表示中质数个计算置位](leetcode/easy/762.go) diff --git a/leetcode/easy/t706/solution.go b/leetcode/easy/t706/solution.go new file mode 100644 index 0000000..073bd0d --- /dev/null +++ b/leetcode/easy/t706/solution.go @@ -0,0 +1,70 @@ +package t706 + +import "container/list" + +type entry struct { + key int + value int +} + +var base = 769 + +// MyHashMap 706. 设计哈希映射 +// https://leetcode.cn/problems/design-hashmap +type MyHashMap struct { + data []list.List +} + +func Constructor() MyHashMap { + return MyHashMap{ + data: make([]list.List, base), + } +} + +func (this *MyHashMap) hash(key int) int { + return key % base +} + +func (this *MyHashMap) Put(key int, value int) { + h := this.hash(key) + // 遍历链表 找到key 如果找到就替换值 + for e := this.data[h].Front(); e != nil; e = e.Next() { + if e.Value.(entry).key == key { + e.Value = entry{key, value} + return + } + } + // 否则插入 + this.data[h].PushBack(entry{key, value}) +} + +func (this *MyHashMap) Get(key int) int { + h := this.hash(key) + // 遍历链表 找到key 如果找到就返回值 + for e := this.data[h].Front(); e != nil; e = e.Next() { + if e.Value.(entry).key == key { + return e.Value.(entry).value + } + } + // 否则返回 -1 + return -1 +} + +func (this *MyHashMap) Remove(key int) { + h := this.hash(key) + // 遍历链表 找到key 如果找到就删除 + for e := this.data[h].Front(); e != nil; e = e.Next() { + if e.Value.(entry).key == key { + this.data[h].Remove(e) + return + } + } +} + +/** + * Your MyHashMap object will be instantiated and called as such: + * obj := Constructor(); + * obj.Put(key,value); + * param_2 := obj.Get(key); + * obj.Remove(key); + */ diff --git a/leetcode/easy/t706/solution_test.go b/leetcode/easy/t706/solution_test.go new file mode 100644 index 0000000..df6ac0c --- /dev/null +++ b/leetcode/easy/t706/solution_test.go @@ -0,0 +1,23 @@ +package t706 + +import "testing" + +func TestMyHashMap(t *testing.T) { + myHashMap := Constructor() + myHashMap.Put(1, 1) + myHashMap.Put(2, 2) + if myHashMap.Get(1) != 1 { + t.Fatal("error") + } + if myHashMap.Get(3) != -1 { + t.Fatal("error") + } + myHashMap.Put(2, 1) + if myHashMap.Get(2) != 1 { + t.Fatal("error") + } + myHashMap.Remove(2) + if myHashMap.Get(2) != -1 { + t.Fatal("error") + } +}