Skip to content

Commit

Permalink
✨706.设计哈希映射
Browse files Browse the repository at this point in the history
  • Loading branch information
techoc committed Apr 15, 2024
1 parent 22164e4 commit d4551bc
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
70 changes: 70 additions & 0 deletions leetcode/easy/t706/solution.go
Original file line number Diff line number Diff line change
@@ -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);
*/
23 changes: 23 additions & 0 deletions leetcode/easy/t706/solution_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}

0 comments on commit d4551bc

Please sign in to comment.