<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.
'Algorithm > 파이썬 알고리즘 인터뷰 스터디' 카테고리의 다른 글
[해시 테이블] 30 중복 문자 없는 가장 긴 부분 문자열(Longest Substring Without Repeating Characters) (0) | 2021.08.21 |
---|---|
[해시 테이블] 29 보석과 돌(Jewels and Stones) (0) | 2021.08.21 |
[데크, 우선순위 큐] 27 k개 정렬 리스트 병합(Merge k Sorted Lists) (0) | 2021.08.21 |
[데크, 우선순위 큐] 26 원형 데크 디자인(Design Circular Deque) (0) | 2021.08.21 |
[스택, 큐] 25 원형 큐 디자인(Design Circular Queue) - 작성중 (0) | 2021.08.16 |