class MyHashMap {
final int LEN = 10000;
ListNode[] buckets;
/** Initialize your data structure here. */
public MyHashMap() {
buckets = new ListNode[LEN];
}
/** value will always be non-negative. */
public void put(int key, int value) {
int index = getIndex(key);
if (buckets[index] == null) {
buckets[index] = new ListNode(-1, -1);
}
ListNode preNode = find(buckets[index], key);
if (preNode.next == null) {
preNode.next = new ListNode(key, value);
}
else {
preNode.next.val = 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 = getIndex(key);
if (buckets[index] == null) {
return -1;
}
ListNode preNode = find(buckets[index], key);
if (preNode.next == null) {
return -1;
}
else {
return preNode.next.val;
}
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
public void remove(int key) {
int index = getIndex(key);
if (buckets[index] == null) {
return;
}
ListNode preNode = find(buckets[index], key);
if (preNode.next == null) {
return;
}
else {
preNode.next = preNode.next.next;
}
}
class ListNode {
int key, val;
ListNode next;
public ListNode(int key, int value) {
this.key = key;
this.val = value;
next = null;
}
}
public int getIndex(int key) {
return Integer.hashCode(key) % LEN;
}
public ListNode find(ListNode bucket, int key) {
ListNode curNode = bucket;
ListNode preNode = null;
while (curNode != null && curNode.key != key) {
preNode = curNode;
curNode = curNode.next;
}
return preNode;
}
}
/**
* 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);
*/