본문 바로가기

Algorithm/파이썬 알고리즘 인터뷰 스터디

[해시 테이블] 28 해시맵 디자인(Design HashMap)

<LeetCode 문제>

https://leetcode.com/problems/design-hashmap/

 

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

다음 기능을 제공하는 해시맵을 디자인하는 문제입니다.

put(key, value): 키,값을 해시맵에 삽입하고, 만약 이미 존재하는 키라면 업데이트한다.

get(key): 키에 해당하는 값을 조회하고, 만약 키가 존재하지 않는다면 -1을 리턴한다.

remove(key): 키에 해당하는 키, 값을 해시맵에서 삭제한다.

<풀이>

class MyHashMap:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.data = [Node() for _ in range(1000)]
        
    def hashcode(self, key):
        size = len(self.data)
        return key % size

    def put(self, key: int, value: int) -> None:
        """
        value will always be non-negative.
        """
        hashcode = self.hashcode(key)
        head = self.data[hashcode]
        while head.next:
            if head.next.key == key:
                head.next.val = value
                return
            head = head.next
        head.next = Node(key, value)
            
        

    def get(self, key: int) -> int:
        """
        Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
        """
        hashcode = self.hashcode(key)
        head = self.data[hashcode]
        while head.next:
            if head.next.key == key:
                return head.next.val
            head = head.next
        return -1

    def remove(self, key: int) -> None:
        """
        Removes the mapping of the specified value key if this map contains a mapping for the key
        """
        hashcode = self.hashcode(key)
        head = self.data[hashcode]
        
        while head.next:
            if head.next.key == key:
                toremove = head.next
                head.next = toremove.next
                toremove.next = None
                return
            head = head.next


class Node:
    def __init__(self, key = -1, val = -1, next = None):
        self.key = key
        self.val = val
        self.next = next

<학습내용>

1.

<학습이 필요한 내용>

1.