LeetCode 706. Design HashMap
考点 | 难度 |
---|---|
Hash Table | Easy |
题目
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.
思路
和705类似,但是这里新建int
的数组,默认值为-1,其他步骤的类似。
答案
class MyHashMap {
private int[] hashMap = new int[1000001];
public MyHashMap() {
for (int i = 0; i < 1000001; ++i){
hashMap[i] = -1;
}
}
public void put(int key, int value) {
hashMap[key] = value;
}
public int get(int key) {
return hashMap[key];
}
public void remove(int key) {
hashMap[key] = -1;
}
}