Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fbe20b9

Browse files
author
Shuo
authored
Merge pull request #527 from openset/develop
Add: Design HashMap
2 parents 3a18733 + 6ab6741 commit fbe20b9

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,36 @@
11
package design_hashmap
2+
3+
type MyHashMap struct {
4+
data map[int]int
5+
}
6+
7+
/** Initialize your data structure here. */
8+
func Constructor() MyHashMap {
9+
return MyHashMap{make(map[int]int, 0)}
10+
}
11+
12+
/** value will always be non-negative. */
13+
func (this *MyHashMap) Put(key int, value int) {
14+
this.data[key] = value
15+
}
16+
17+
/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
18+
func (this *MyHashMap) Get(key int) int {
19+
if v, ok := this.data[key]; ok {
20+
return v
21+
}
22+
return -1
23+
}
24+
25+
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
26+
func (this *MyHashMap) Remove(key int) {
27+
delete(this.data, key)
28+
}
29+
30+
/**
31+
* Your MyHashMap object will be instantiated and called as such:
32+
* obj := Constructor();
33+
* obj.Put(key,value);
34+
* param_2 := obj.Get(key);
35+
* obj.Remove(key);
36+
*/
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,18 @@
11
package design_hashmap
2+
3+
import "testing"
4+
5+
func TestDesignHashmap(t *testing.T) {
6+
obj := Constructor()
7+
obj.Put(1, 1)
8+
obj.Put(2, 2)
9+
output := obj.Get(1) == 1
10+
output = obj.Get(3) == -1 && output
11+
obj.Put(2, 1)
12+
output = obj.Get(2) == 1 && output
13+
obj.Remove(2)
14+
output = obj.Get(2) == -1 && output
15+
if !output {
16+
t.Fatalf("output: %v, expected: %v", output, true)
17+
}
18+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /