Skip to content

Commit c0ca330

Browse files
committed
Add solution #706
1 parent c93c52d commit c0ca330

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@
134134
700|[Search in a Binary Search Tree](./0700-search-in-a-binary-search-tree.js)|Easy|
135135
701|[Insert into a Binary Search Tree](./0701-insert-into-a-binary-search-tree.js)|Medium|
136136
704|[Binary Search](./0704-binary-search.js)|Easy|
137+
706|[Design HashMap](./0706-design-hashmap.js)|Easy|
137138
713|[Subarray Product Less Than K](./0713-subarray-product-less-than-k.js)|Medium|
138139
722|[Remove Comments](./0722-remove-comments.js)|Medium|
139140
733|[Flood Fill](./0733-flood-fill.js)|Easy|

solutions/0706-design-hashmap.js

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* 706. Design HashMap
3+
* https://leetcode.com/problems/design-hashmap/
4+
* Difficulty: Easy
5+
*
6+
* Design a HashMap without using any built-in hash table libraries.
7+
* Implement the MyHashMap class:
8+
* - MyHashMap() initializes the object with an empty map.
9+
* - void put(int key, int value) inserts a (key, value) pair into the HashMap.
10+
* If the key already exists in the map, update the corresponding value.
11+
* - int get(int key) returns the value to which the specified key is mapped,
12+
* or -1 if this map contains no mapping for the key.
13+
* - void remove(key) removes the key and its corresponding value if the map
14+
* contains the mapping for the key.
15+
*/
16+
17+
18+
var MyHashMap = function() {
19+
this._keys = [];
20+
this._values = [];
21+
};
22+
23+
/**
24+
* @param {number} key
25+
* @param {number} value
26+
* @return {void}
27+
*/
28+
MyHashMap.prototype.put = function(key, value) {
29+
if (this._keys[key] === undefined) {
30+
this._values.push(value);
31+
this._keys[key] = this._values.length - 1;
32+
} else {
33+
this._values[this._keys[key]] = value;
34+
}
35+
};
36+
37+
/**
38+
* @param {number} key
39+
* @return {number}
40+
*/
41+
MyHashMap.prototype.get = function(key) {
42+
const offset = this._keys[key];
43+
return offset === undefined ? -1 : this._values[offset];
44+
}
45+
/**
46+
* @param {number} key
47+
* @return {void}
48+
*/
49+
MyHashMap.prototype.remove = function(key) {
50+
if (this._keys[key] !== undefined) {
51+
this._values[this._keys[key]] = undefined;
52+
this._keys[key] = undefined;
53+
}
54+
};

0 commit comments

Comments
 (0)