# Leetcode 706. Design HashMap

## 2. Solution

• Version 1
```class MyHashMap:

def __init__(self):
self.maps = [[] for _ in range(1000)]

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

def get(self, key: int) -> int:
index = self.hash(key)
for k, v in self.maps[index]:
if k == key:
return v
return -1

def remove(self, key: int) -> None:
index = self.hash(key)
for k, v in self.maps[index]:
if k == key:
self.maps[index].remove([k, v])
break

def hash(self, key):
return key % 1000```
• Version 2
```class ListNode:
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None

class MyHashMap:

def __init__(self):
self.maps = [None] * 1000

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

if self.maps[index] is None:
self.maps[index] = ListNode(key, value)
else:
current = self.maps[index]
while True:
if current.key == key:
current.value = value
break
elif current.next is None:
current.next = ListNode(key, value)
break
current = current.next

def get(self, key: int) -> int:
index = self.hash(key)
current = self.maps[index]
while current:
if current.key == key:
return current.value
current = current.next
return -1

def remove(self, key: int) -> None:
index = self.hash(key)
current = self.maps[index]
if current is not None and current.key == key:
self.maps[index] = current.next
else:
while current:
if current.key == key:
pre.next = current.next
break
pre = current
current = current.next

def hash(self, key):
return key % 1000```

## Reference

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

0 条评论

• ### LeetCode 706：设计哈希映射 Design HashMap

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

• ### 【设计数据结构】面试官：请设计一个简单的 HashMap ...

与 705. 设计哈希集合 同理，我们可以利用「链表」来构建 Map，这也是工程上最简单的一种实现方式。

• ### 数据结构设计题

What to return for each function? Size of data?

• ### 算法细节系列（30）：接口设计

版权声明：本文为博主原创文章，未经博主允许不得转载。 https://blog.csdn.n...

• ### LeetCode Weekly Contest 36解题思路

版权声明：本文为博主原创文章，未经博主允许不得转载。 https://blog.csdn.n...

• ### 有关 HashMap 面试会问的一切

比如 Leetcode 第一题 Two Sum 的某种变种的最优解就是需要用到 HashMap 的，高频考题 LRU Cache 是需要用到 LinkedHas...

• ### LeetCode Weekly Contest 46解题思路

版权声明：本文为博主原创文章，未经博主允许不得转载。 https://blog.csdn.n...