1. 题目
题目链接706. 设计哈希映射
2. 思路
主要是利用ArrayList数组,保存自己写的类Map,里面有key和value,然后设置一个合理的长度BUCKETS,生成哈希函数的值,每次将key转换为hash值,然后使用Iterator遍历做删除,插入和查询操作即可。
3. 代码
class MyHashMap {
/** Initialize your data structure here. */
private class Map {
public int key;
public int value;
public Map(int key, int value) {
this.key = key;
this.value = value;
}
public Map() {}
}
private static final int BUCKETS = 1009;
private ArrayList[] hashMap;
public MyHashMap() {
hashMap = new ArrayList[BUCKETS];
for (int i = 0; i < BUCKETS; i++) {
hashMap[i] = new ArrayList<Map>();
}
}
/** value will always be non-negative. */
public void put(int key, int value) {
int index = hash(key);
Iterator<Map> iterator = hashMap[index].iterator();
while (iterator.hasNext()) {
Map map = iterator.next();
if (map.key == key) {
map.value = value;
return;
}
}
hashMap[index].add(new Map(key, value));
}
/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
public int get(int key) {
int index = hash(key);
Iterator<Map> iterator = hashMap[index].iterator();
while (iterator.hasNext()) {
Map map = iterator.next();
if (map.key == key) {
return map.value;
}
}
return -1;
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
public void remove(int key) {
int index = hash(key);
Iterator<Map> iterator = hashMap[index].iterator();
while (iterator.hasNext()) {
Map map = iterator.next();
if (map.key == key) {
hashMap[index].remove(map);
return;
}
}
}
public int hash(int key) {
return key % BUCKETS;
}
}
/**
* Your MyHashMap object will be instantiated and called as such:
* MyHashMap obj = new MyHashMap();
* obj.put(key,value);
* int param_2 = obj.get(key);
* obj.remove(key);
*/