用列表构建:
class MyHashMap {
class Node{
int key;
int value;
public Node(int key,int value){
this.key = key;
this.value = value;
}
}
List<List<Node>> list = new ArrayList<>(10000);
/** Initialize your data structure here. */
public MyHashMap() {
for(int i=0;i<10000;i++){
list.add(new LinkedList<Node>());
}
}
/** value will always be non-negative. */
public void put(int key, int value) {
List<Node> tmp = list.get(key%10000);
for(int i=0;i<tmp.size();i++){
if(tmp.get(i).key==key){
tmp.get(i).value = value;
return;
}
}
tmp.add(new Node(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) {
List<Node> tmp = list.get(key%10000);
for(int i=0;i<tmp.size();i++){
if(tmp.get(i).key==key){
return tmp.get(i).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) {
List<Node> tmp = list.get(key%10000);
for(int i=0;i<tmp.size();i++){
if(tmp.get(i).key==key){
tmp.remove(i);
return;
}
}
}
}
要明白java中的命名都是引用,所以才能在代码中针对tmp(一个临时的命名)进行修改时,也就更改了真正的存储位置的东西。