package cn.learn.datastructor.leetcode;
import java.util.Iterator;
import java.util.LinkedList;
public class MyHashMap {
// 数量可以是动态的,此时需要rehash了
int size = 10000;
Entry[] table;
/** Initialize your data structure here. */
public MyHashMap() {
table = new Entry[size];
}
/** value will always be non-negative. */
public void put(int key, int value) {
int index;
Entry e;
Node n = new Node(key, value);
if ((e = table[index = hash(key)]) == null) {
e = new Entry();
e.addNode(n);
table[index] = e;
} else {
Iterator<Node> iterator = e.nodeList.iterator();
while (iterator.hasNext()) {
Node next = iterator.next();
if (next.key == key) {
next.value = value;
return;
}
}
e.addNode(n);
}
}
private int hash(int key) {
return key % size;
}
/** 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) {
Entry e;
if ((e = table[hash(key)]) != null) {
Iterator<Node> iterator = e.nodeList.iterator();
while (iterator.hasNext()) {
Node next = iterator.next();
if (next.key == key) {
return next.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) {
Entry e;
if ((e = table[hash(key)]) != null) {
Iterator<Node> iterator = e.nodeList.iterator();
while (iterator.hasNext()) {
Node next = iterator.next();
if (next.key == key) {
e.nodeList.remove(next);
return;
}
}
}
}
class Entry<Node> {
LinkedList<Node> nodeList;
void addNode(Node n) {
if (nodeList == null) {
nodeList = new LinkedList<>();
}
nodeList.addLast(n);
}
}
class Node{
int key;
int value;
public Node(int key, int value) {
this.key = key;
this.value = value;
}
}
}