|
| 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