-
Notifications
You must be signed in to change notification settings - Fork 1
/
my-hash-map.go
122 lines (98 loc) · 1.89 KB
/
my-hash-map.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package hashTable
// 706
type LinkNode struct {
value int
key int
next *LinkNode
}
// 706
type MyHashMap struct {
list [500]LinkNode
}
/** Initialize your data structure here. */
func ConstructorMap() MyHashMap {
o := MyHashMap{
list: [500]LinkNode{},
}
for i := 0; i < len(o.list); i++ {
o.list[i].value = -1
}
return o
}
func (this *MyHashMap) hashKey(key int) int {
M := 101
return key % M
}
/** value will always be non-negative. */
func (this *MyHashMap) Put(key int, value int) {
i := this.hashKey(key)
node := &this.list[i]
if node.value == -1 || node.key == key {
node.value = value
node.key = key
} else {
for node.next != nil {
node = node.next
if node.key == key {
node.value = value
goto NOT
}
}
valNode := LinkNode{
value: value,
key: key,
}
for node.next != nil {
node = node.next
}
node.next = &valNode
}
NOT:
}
/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
func (this *MyHashMap) Get(key int) int {
i := this.hashKey(key)
node := &this.list[i]
for node.next != nil {
if node.key == key {
return node.value
} else {
node = node.next
}
}
if node.key != key {
return -1
}
return node.value
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
func (this *MyHashMap) Remove(key int) {
i := this.hashKey(key)
node := &this.list[i]
if node.key == key {
if node.next == nil {
*node = LinkNode{
value: -1,
}
} else {
*node = *node.next
}
} else {
upNode := node
for node.next != nil {
upNode = node
node = node.next
if node.key == key {
upNode.next = node.next
break
}
}
}
}
/**
* Your MyHashMap object will be instantiated and called as such:
* obj := Constructor();
* obj.Put(key,value);
* param_2 := obj.Get(key);
* obj.Remove(key);
*/