넘치게 채우기

[LeetCode] 706. Design HashMap 본문

PS/LeetCode

[LeetCode] 706. Design HashMap

riveroverflow 2023. 10. 4. 10:40
728x90
반응형

https://leetcode.com/problems/design-hashmap/description/?envType=daily-question&envId=2023-10-04 

 

LeetCode - The World's Leading Online Programming Learning Platform

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

문제 유형 : 구현 / 해시

문제 난이도 : Easy

 

문제

Design a HashMap without using any built-in hash table libraries.

Implement the MyHashMap class:

  • MyHashMap() initializes the object with an empty map.
  • void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, 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(key) removes the key and its corresponding value if the map contains the mapping for the key.

라이브러리를 사용하지 않고 해시맵을 구현하라. 

put, get, remove 메서드를 구현하면 된다.

 

풀이

vector<pair<int, int>>형태의 자료구조를 만들어서, key-value쌍을 가지는 빈 배열을 생성한다.

 

put 메서드 - pair.first가 key를 가지고 있다면, 그 값을 바꿔준다. 없으면 새로 key-value쌍을 배열에 추가해준다.

get 메서드 - pair.first가 key를 가지고 있다면, 그 값을 반환한다. 없으면 -1을 반환한다.

remove 메서드 - pair.first를 찾아 순회하여, 찾으면 그 key-value쌍을 없앤다.

 

코드

C++

class MyHashMap {
public:

    vector<pair<int, int>> map;

    MyHashMap() {
        
    }
    
    void put(int key, int value) {
        for(auto& p : map) {
            if(p.first == key) {
                p.second = value;
                return;
            }
        }
        map.push_back(make_pair(key, value));
    }
    
    int get(int key) {
        for(auto p : map) {
            if(p.first == key) {
                return p.second;
            }
        }
        return -1;
    }
    
    void remove(int key) {
        for(auto it = map.begin(); it != map.end(); it++) {
            if(it -> first == key) {
                map.erase(it);
                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);
 */
 
728x90
반응형