学个屁啊 无语子
题目
https://leetcode-cn.com/problems/design-hashmap/
代码
用链表呗
class MyHashMap {
private class Node{
int key;
int value;
public Node(int k,int v){
key=k;
value=v;
}
public int getKey(){
return key;
}
public int getValue(){
return value;
}
public void setKey(int k){
key=k;
}
public void setValue(int v){
value=v;
}
}
LinkedList[] data;
static final int BASE=769;
public MyHashMap() {
//初始化链表数组
data=new LinkedList[BASE];
for(int i=0;i<BASE;i++){
data[i]=new LinkedList<Node>();
}
}
/** value will always be non-negative. */
public void put(int key, int value) {
LinkedList<Node> list=data[hash(key)];
//没有key对应元素,插入一个新结点
if(get(key)==-1){
list.addLast(new Node(key,value));
}
else{
Iterator<Node> iterator=list.iterator();
while(iterator.hasNext()){
Node n=iterator.next();
if(n.getKey()==key){//找到Key对应节点
n.setValue(value);//更改value
break;
}
}
}
}
/** 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) {
LinkedList<Node> list=data[hash(key)];
Iterator<Node> iterator=list.iterator();
while(iterator.hasNext()){
Node n=iterator.next();
if(n.getKey()==key){
return n.getValue();
}
}
return -1;
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
public void remove(int key) {
LinkedList<Node> list=data[hash(key)];
Iterator<Node> iterator=list.iterator();
int i=0;//节点的索引位置
boolean flag=false;//是否有这个节点
while(iterator.hasNext()){
Node n=iterator.next();
if(n.getKey()==key){
flag=true;
break;
}
i++;
}
//有这个节点
if(flag)
list.remove(i);//删除Index为i的节点
}
public int hash(int key){
return key%BASE;
}
}
/**
* 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);
*/