
문제 : LeetCode 706. Design HashMap
(https://leetcode.com/problems/design-hashmap/description/)
해시맵을 이용하여 <key, value>를 put, get, remove하는 함수를 구현하라.
1) 해시맵에 대한 이해
C++ map, unordered_map 정리
#include <vector>
#define SIZE 10000
class MyHashMap {
private:
vector<vector<pair<int, int>>> hv;
int hashKey;
public:
MyHashMap() : hv(SIZE) {
}
void put(int key, int value) {
hashKey = key%SIZE;
if (hv[hashKey].empty()) {
hv[hashKey].push_back({key, value});
return;
}
for(auto& k : hv[hashKey]) {
if (k.first == key) {
k.second = value;
return;
}
}
hv[hashKey].push_back({key, value});
return;
}
int get(int key) {
hashKey = key%SIZE;
if (hv[hashKey].empty()) return -1;
for (auto& k : hv[hashKey]) {
if (k.first == key) return k.second;
}
return -1;
}
void remove(int key) {
hashKey = key%SIZE;
if (hv[hashKey].empty()) return;
for (auto it = hv[hashKey].begin(); it != hv[hashKey].end(); it++) {
if (it->first == key) {
hv[hashKey].erase(it);
return;
}
}
return;
}
};
/**
* Your MyHashMap object will be instantiated and called as such:
* MyHashMap* obj = new MyHashMap();
* obj->put(key,value);
* int param_2 = obj->get(key);
* obj->remove(key);
*/
함수 기능뿐 아니라 요구하는 구조에 맞게 구현하도록 하자.