Design HashMap Problem
Problem
Design a HashMap without using any built-in hash table libraries.
Implement the MyHashMap
class:
MyHashMap()
initializes the object with an empty map.void put(int key, int value)
inserts a(key, value)
pair into the HashMap. If thekey
already exists in the map, update the correspondingvalue
.int get(int key)
returns thevalue
to which the specifiedkey
is mapped, or-1
if this map contains no mapping for thekey
.void remove(key)
removes thekey
and its correspondingvalue
if the map contains the mapping for thekey
.
Examples
Example 1:
|
|
Constraints
0 <= key, value <= 10^6
- At most
10^4
calls will be made toput
,get
, andremove
.
Solution
Method 1 - Using Array of LinkedList
The map is generally an array based structure. But if we store only one value at array index, we may have issues with collisions.
Our list class:
|
|
Nnw we need hash function, we can use Integer.hashCode() on key.
- Put call - Each time from hash-code, we go to index in array. If we don’t see any value there, that is no collision and we simply add the values to map. If there is a collision, there are 2 cases -
- same key is added to map, so nothing to do just set the latest value.
- different key is added to map, so just appended it to linked list
- Get call - Use hash function, and get the value. Traverse list and get the values
- Remove call - Use hash function, get the array index and remove the key from linked list
Full Implementation
|
|