반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 706 | Design HashMap | Python 본문
728x90
반응형
문제 링크: https://leetcode.com/problems/design-hashmap/
문제
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.
조건
- 0 <= key, value <= 106
- At most 104 calls will be made to put, get, and remove.
내 풀이
705 | Design HashSet와 같이 풀지만, 다른점은 value가 주어진다는 점이다.
처음에 hashset을 만들 때 -1로 초기화한다. 왜냐하면 나중에 get함수를 만들 때 값이 존재하지 않는다면 -1을 리턴해야하기 때문이다.
다음부터는 705번 문제와 같다.
self.hash[key] = value에 저장하고, 없앨 때는 값을 -1로 바꾼다.
코드
class MyHashMap:
def __init__(self):
self.hash = [-1 for _ in range(1000001)]
def put(self, key: int, value: int) -> None:
self.hash[key] = value
def get(self, key: int) -> int:
return self.hash[key]
def remove(self, key: int) -> None:
self.hash[key] = -1
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)
728x90
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 1584 | Min Cost to Connect All Points | Python (0) | 2022.04.26 |
---|---|
[LeetCode] 284 | Peeking Iterator | Python (0) | 2022.04.25 |
[LeetCode] 705 | Design HashSet | Python (0) | 2022.04.21 |
[LeetCode] 173 | Binary Search Tree Iterator | Python (0) | 2022.04.20 |
[LeetCode] 99 | Recover Binary Search Tree | Python (0) | 2022.04.19 |
Comments