Package g0701_0800.s0706_design_hashmap
Class MyHashMap
java.lang.Object
g0701_0800.s0706_design_hashmap.MyHashMap
706 - Design HashMap.<p>Easy</p>
<p>Design a HashMap without using any built-in hash table libraries.</p>
<p>Implement the <code>MyHashMap</code> class:</p>
<ul>
<li><code>MyHashMap()</code> initializes the object with an empty map.</li>
<li><code>void put(int key, int value)</code> inserts a <code>(key, value)</code> pair into the HashMap. If the <code>key</code> already exists in the map, update the corresponding <code>value</code>.</li>
<li><code>int get(int key)</code> returns the <code>value</code> to which the specified <code>key</code> is mapped, or <code>-1</code> if this map contains no mapping for the <code>key</code>.</li>
<li><code>void remove(key)</code> removes the <code>key</code> and its corresponding <code>value</code> if the map contains the mapping for the <code>key</code>.</li>
</ul>
<p><strong>Example 1:</strong></p>
<p><strong>Input</strong></p>
<p>[“MyHashMap”, “put”, “put”, “get”, “get”, “put”, “get”, “remove”, “get”]</p>
<p>[ [], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]</p>
<p><strong>Output:</strong> [null, null, null, 1, -1, null, 1, null, -1]</p>
<p><strong>Explanation:</strong></p>
<pre><code> MyHashMap myHashMap = new MyHashMap();
myHashMap.put(1, 1); // The map is now [[1,1]]
myHashMap.put(2, 2); // The map is now [[1,1], [2,2]]
myHashMap.get(1); // return 1, The map is now [[1,1], [2,2]]
myHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]]
myHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value)
myHashMap.get(2); // return 1, The map is now [[1,1], [2,1]]
myHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]
myHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]]
</code></pre>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= key, value <= 10<sup>6</sup></code></li>
<li>At most <code>10<sup>4</sup></code> calls will be made to <code>put</code>, <code>get</code>, and <code>remove</code>.</li>
</ul>
-
Constructor Summary
Constructors -
Method Summary
-
Constructor Details
-
MyHashMap
public MyHashMap()
-
-
Method Details
-
put
public void put(int key, int value) -
get
public int get(int key) -
remove
public void remove(int key)
-