class MyHashMap {
public class Entry {
public int key;
public int value;
public Entry(int k, int v) {
key = k;
value = v;
}
}
private Entry[] data;
private static final int SIZE = 13_333; // 10000 / 0.75
private static final int DELETED = -1;
public MyHashMap() {
data = new Entry[SIZE];
}
public void put(int key, int value) {
data[hash(key)] = new Entry(key, value);
}
public int get(int key) {
Entry entry = data[hash(key)];
return entry == null ? -1 : entry.value;
}
public void remove(int key) {
data[hash(key)] = new Entry(DELETED, DELETED);
}
private int hash(int key) {
int i = key % SIZE;
while (data[i] != null && data[i].key != key) {
i = (i + 1) % SIZE;
}
return i;
}
}
function linkNode(key,val){
this.key=key;
this.val=val;
this.next=null;
}
var MyHashMap = function() {
const N=2011;
const hash=new Array(N);
for(let i=0;i<hash.length;i++){
hash[i]=new linkNode();
}
this.hash=hash;
};
/**
- value will always be non-negative.
- @param {number} key
- @param {number} value
- @return {void}
*/
MyHashMap.prototype.put = function(key, value) {
const N=2011;
const index=key%N;
let head=this.hash[index];
let cur=head;
while(cur && cur.next){
if(cur.next.key===key){
cur.next.val=value;
return ;
}
cur=cur.next;
}
const node=new linkNode(key,value);
cur.next=node;
};
/**
- Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
- @param {number} key
- @return {number}
*/
MyHashMap.prototype.get = function(key) {
const N=2011;
const index=key%N;
let head=this.hash[index];
let cur=head;
while(cur && cur.next){
if(cur.next.key===key){
return cur.next.val;
}
cur=cur.next;
}
return -1;
};
/**
- Removes the mapping of the specified value key if this map contains a mapping for the key
- @param {number} key
- @return {void}
*/
MyHashMap.prototype.remove = function(key) {
const N=2011;
const index =key%N;
let head=this.hash[index];
let cur=head;
while(cur && cur.next){
if(cur.next.key===key){
cur.next=cur.next.next;
}
cur=cur.next;
}
};
/**
- Your MyHashMap object will be instantiated and called as such:
- var obj = new MyHashMap()
- obj.put(key,value)
- var param_2 = obj.get(key)
- obj.remove(key)
*/