티스토리 뷰

leetcode.com/problems/design-hashmap/submissions/

 

Design HashMap - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Hash table관련 라이브러리 없이 작동하는 객체를 만들라고한다.

class MyHashMap {
private:
public:
    vector<pair<int, int>> map;
    MyHashMap() {}
    ~MyHashMap() { map.clear(); }

    void put(int key, int value) {
        if (get(key) == -1) map.push_back(pair<int, int>(key, value));
        else {
            remove(key);
            map.push_back(pair<int, int>(key, value));
        }
    }
    
    int get(int key) {
        for (int i = 0; i < map.size(); i++) {
            if(map[i].first == key) return map[i].second;
        }
        return -1;
    }
    
    void remove(int key) {
        for (int i = 0; i < map.size(); i++) {
            if (map[i].first == key) map.erase(map.begin() + i);
        }
    }
};

put은 hashmap에 Data를 insert하도록 동작(이미 같은값의 key가 존재할 경우 value를 갱신)

get은 key값에 대한 value를 return하도록 하고, key가 없을경우 -1을 return

remove는 일치하면 key값이 있으면 객체 내에서 제거하면 된다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함