새소식

Study/문제풀이

[leetcode] 리트코드 706번 해시맵 디자인

  • -
728x90

이 책을 보고 문제를 풉니다.

※문제 해석은 책 그대로 쓰지 않고 직접 합니다.

리트코드 706. 해시맵 디자인

1. 문제 

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

빌트인 해쉬 테이블 라이브러리를 사용하지 말고 해시맵을 디자인하세요.

Implement the MyHashMap class:

  • MyHashMap() initializes the object with an empty map.
    MyHashMap()은 빈 맵으로 초기화합니다.
  • 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.
    put(key, 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.
    get(key)는 키가 맵핑된 값을 리턴합니다. 맵핑된 값이 없을 경우 (존재하지 않는 키일 경우) -1를 리턴합니다.
  • void remove(key) removes the key and its corresponding value if the map contains the mapping for the key.
    remove(key)는 해시맵에 key가 존재할 경우 키,값 쌍을 삭제합니다.

2. 풀이

Chater 11 풀이 깃허브 링크

class MyHashMap:

    def __init__(self):
        self.hash = dict()

    def put(self, key: int, value: int) -> None:
        self.hash[key] = value

    def get(self, key: int) -> int:
        try:
            return self.hash[key]
        except:
            return -1

    def remove(self, key: int) -> None:
        try:
            return self.hash.pop(key)
        except:
            return

 왜이렇게 간단해? 싶었는데 책은 조금 더 디테일하고 정확한 문제풀이를 해둔 걸 보실 수 있습니다. 충돌하는 해쉬 값이 있을 경우 추가적으로 탐색하지 않고 그대로 덮어쓰기 때문에 가능한 풀이 같습니다. 기능만 제대로 하면 문제풀이야 쉽지만 문제가 출제된 의도와 그로부터 배울 수 있는 CS적인 마인드는 이런 구체적인 해설이 있어야 얻을 수 있지 않나 생각합니다. 


근황 공유 스터디 알고리즘 스터디에 오랜만에 끼고 싶어서 풀어봤습니다.

728x90
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.