Problem Solving/LeetCode

[LeetCode] C++ 706. Design HashMap

LeeJaeJun 2024. 8. 26. 23:59
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
반응형