-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdesign-hashmap.go
105 lines (87 loc) · 1.76 KB
/
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
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
package designhashmap
type MyHashMap struct {
buckets []*Entry
size int
}
type Entry struct {
key int
value int
next *Entry
}
/** Initialize your data structure here. */
func Constructor() MyHashMap {
return MyHashMap{buckets: make([]*Entry, 13), size: 13}
}
/** value will always be non-negative. */
func (this *MyHashMap) Put(key int, value int) {
i := this.getIndex(key)
curr := this.buckets[i]
if curr == nil {
this.buckets[i] = &Entry{key: key, value: value}
return
}
for curr.next != nil {
if curr.key == key {
curr.value = value
return
}
curr = curr.next
}
if curr.key == key {
curr.value = value
} else {
curr.next = &Entry{key: key, value: value}
}
}
/** 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.getIndex(key)
curr := this.buckets[i]
if curr == nil {
return -1
}
for curr != nil {
if curr.key == key {
return curr.value
}
curr = curr.next
}
return -1
}
/** 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.getIndex(key)
curr := this.buckets[i]
var prev *Entry
if curr == nil {
return
}
for curr != nil {
if curr.key == key {
if prev == nil {
this.buckets[i] = curr.next
} else {
next := curr.next
prev.next = next
curr.next = nil
}
return
}
prev = curr
curr = curr.next
}
}
func (this *MyHashMap) getIndex(key int) int {
i := key * 12582917 % this.size
if i < 0 {
i *= -1
}
return i
}
/**
* Your MyHashMap object will be instantiated and called as such:
* obj := Constructor();
* obj.Put(key,value);
* param_2 := obj.Get(key);
* obj.Remove(key);
*/