728x90
반응형
https://leetcode.com/problems/design-hashmap/description/
문제
문제 분석
- 개별 체이닝 방식으로 hashMap을 구현하였습니다
풀이
class MyHashMap {
private:
static const int SIZE = 1000;
struct Node{
int key;
int value;
Node* next;
Node(int k, int v):key(k), value(v), next(nullptr){}
};
vector<Node*> map;
public:
MyHashMap() {
map.resize(SIZE, nullptr);
}
void put(int key, int value) {
int index = key % SIZE;
if(map[index] == nullptr){
map[index] = new Node(key, value);
}else{
Node* current = map[index];
while(current->next != nullptr && current->key != key){
current = current->next;
}
if(current->key == key){
current->value = value;
}else{
current->next = new Node(key, value);
}
}
}
int get(int key) {
int index = key % SIZE;
Node* current = map[index];
while(current != nullptr){
if(current->key == key){
return current->value;
}
current = current->next;
}
return -1;
}
void remove(int key) {
int index = key % SIZE;
if(map[index] == nullptr){
return;
}else{
Node* previous = nullptr;
Node* current = map[index];
while(current != nullptr){
if(current->key == key){
if(previous == nullptr){
map[index] = current->next;
}else{
previous->next = current->next;
}
delete current;
return;
}
previous = current;
current = current->next;
}
}
}
};
728x90
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
[LeetCode] C++ 17. Letter Combinations of a Phone Number (4) | 2024.09.01 |
---|---|
[LeetCode] C++ 200. Number of Islands (0) | 2024.09.01 |
[LeetCode] C++ 23. Merge k Sorted Lists. (0) | 2024.08.25 |
[LeetCode] C++ 739. Daily Temperatures (0) | 2024.08.19 |
[LeetCode] C++ 316. Remove Duplicate Letters (0) | 2024.08.18 |