Design a HashMap without using any built-in hash table libraries. Implement the following functions:
MyHashMap()
: Initializes the object.void put(int key, int value)
: Inserts a key-value pair into the HashMap. If the key already exists in the HashMap, update the corresponding value.int get(int key)
: Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.void remove(int key)
: Removes the key and its corresponding value if the map contains the mapping for the key.0 <= key, value <= 1,000,000
for this problem.10000
) can be used, assuming it as reasonably large enough and not requiring dynamic resizing.hash = key % capacity
.#include <vector>
#include <list>
#include <utility>
class MyHashMap {
private:
static const int capacity = 10000; // Capacity of the HashMap
std::vector<std::list<std::pair<int, int>>> data;
int hash(int key) {
return key % capacity; // Simple hash function
}
public:
MyHashMap() : data(capacity) {}
void put(int key, int value) {
int hashedKey = hash(key);
for (auto& [k, v] : data[hashedKey]) {
if (k == key) {
v = value;
return;
}
}
data[hashedKey].emplace_back(key, value);
}
int get(int key) {
int hashedKey = hash(key);
for (const auto& [k, v] : data[hashedKey]) {
if (k == key) return v;
}
return -1;
}
void remove(int key) {
int hashedKey = hash(key);
auto& list = data[hashedKey];
for (auto it = list.begin(); it != list.end(); ++it) {
if (it->first == key) {
list.erase(it);
return;
}
}
}
};
MyHashMap()
): O(1) - Initializing the vector with a fixed capacity.Here, n
refers to the number of key-value pairs in a single bucket (linked list), but typically due to the hash function, operations should be average O(1) if the keys are distributed uniformly.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?