-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0706-design-hashmap.go
71 lines (63 loc) · 1.17 KB
/
0706-design-hashmap.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
type Node struct {
Key int
Val int
Next *Node
}
func NewNode(key, val int) *Node {
return &Node{
Key: key,
Val: val,
}
}
type MyHashMap struct {
Array []*Node
}
func Constructor() MyHashMap {
var arr []*Node
for i := 0; i < 512; i++ {
arr = append(arr, NewNode(-1, -1))
}
return MyHashMap{
Array: arr,
}
}
func (this *MyHashMap) hash(key int) int {
return key % len(this.Array)
}
func (this *MyHashMap) Put(key int, value int) {
cur := this.Array[this.hash(key)]
for cur.Next != nil {
if cur.Next.Key == key {
cur.Next.Val = value
return
}
cur = cur.Next
}
cur.Next = NewNode(key, value)
}
func (this *MyHashMap) Get(key int) int {
cur := this.Array[this.hash(key)]
for cur.Next != nil {
if cur.Next.Key == key {
return cur.Next.Val
}
cur = cur.Next
}
return -1
}
func (this *MyHashMap) Remove(key int) {
cur := this.Array[this.hash(key)]
for cur.Next != nil && cur.Next.Key != key {
cur = cur.Next
}
if cur != nil && cur.Next != nil {
cur.Next = cur.Next.Next
}
}
/**
* Your MyHashMap object will be instantiated and called as such:
* obj := Constructor();
* obj.Put(key,value);
* param_2 := obj.Get(key);
* obj.Remove(key);
*/