[LeetCode] Design HashMap

아르당·2026년 2월 18일

LeetCode

목록 보기
158/213
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

내장된 해시 테이블 라이브러리를 사용하지 않고 HashMap을 설계해라.

MyHashMap 클래스를 구현해라.

  • MyHashMap()는 객체를 빈 map으로 초기화한다.
  • void put(int key, int value)는 (key, value) 쌍으로 HashMap으로 삽입한다. 만약 해당 key가 map에 존재한다면, 그에 상응하는 값을 업데이트한다.
  • int get(int key)는 지정된 키에 매핑된 값을 반환하거나, 해당 키에 대한 매핑이 없다면 -1을 반환한다.
  • void remove(key)는 map에 해당 키에 대한 매핑이 포함되어 있으면 해당키와 그에 상응하는 값을 제거한다.

Example

Input
["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"][], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]
Output
[null, null, null, 1, -1, null, 1, null, -1]
Explanation
MyHashMap myHashMap = new MyHashMap();
myHashMap.put(1, 1); // The map is now [[1,1]]
myHashMap.put(2, 2); // The map is now [[1,1], [2,2]]
myHashMap.get(1); // return 1, The map is now [[1,1], [2,2]]
myHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]]
myHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value)
myHashMap.get(2); // return 1, The map is now [[1,1], [2,1]]
myHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]
myHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]]

Constraints

  • 0 <= key, value <= 10^6
  • put, get, remove는 최대 10^4번 호출된다.

Solved

class Node {
    int key;
    int val;
    Node next;

    Node(int key, int val) {
        this.key = key;
        this.val = val;
        this.next = null;
    }
}

class MyHashMap {
    private Node[] map;

    public MyHashMap() {
        map = new Node[1000];

        for(int i = 0; i < 1000; i++){
            map[i] = new Node(-1, -1);
        }
    }
    
    public void put(int key, int value) {
        int hash = hash(key);
        Node cur = map[hash];

        while(cur.next != null){
            if(cur.next.key == key){
                cur.next.val = value;
                return;
            }

            cur = cur.next;
        }

        cur.next = new Node(key, value);
    }
    
    public int get(int key) {
        int hash = hash(key);
        Node cur = map[hash].next;

        while(cur != null){
            if(cur.key == key){
                return cur.val;
            }
            
            cur = cur.next;
        }

        return -1;
    }
    
    public void remove(int key) {
        int hash = hash(key);
        Node cur = map[hash];

        while(cur.next != null){
            if(cur.next.key == key){
                cur.next = cur.next.next;
                return;
            }

            cur = cur.next;
        }
    }

    private int hash(int key) {
        return key % 1000;
    }
}

/**
 * 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);
 */
profile
내 마음대로 코드 작성하는 세상

0개의 댓글