706. Design HashMap
//This method use the index bucket. Data is stored as linked-list
public class MyHashMap {
class Data {
int key, val;
Data next;
Data(int key, int val) {
this.key = key;
this.val = val;
}
}
Data[] map;
int size;
/** Initialize your data structure here. */
public MyHashMap() {
map = new Data[10];
}
/** value will always be non-negative. */
public void put(int key, int value) {
int hash = key % map.length;
if (map[hash] == null) {
map[hash] = new Data(key, value);
} else if (map[hash].key == key) {
map[hash].val = value;
} else { //need to link to the last Data
Data d = map[hash];
while (d.next != null && d.next.key != key) d = d.next;
if (d.next != null) d.next.val = value;
else d.next = new Data(key, value);
}
size++;
if (size * 1.0 / map.length > 0.75) rehash();
}
/** 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 hash = key % map.length;
Data d = map[hash];
while (d != null) {
if (d.key == key) return d.val;
else d = d.next;
}
return -1;
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
public void remove(int key) {
int hash = key % map.length;
if (map[hash] == null) return;
if (map[hash].key == key) map[hash] = map[hash].next;
else {
Data d = map[hash];
while (d.next != null && d.next.key != key) d = d.next; //find the d.next.key == key to remove
if (d.next != null) d.next = d.next.next; //if there is a next one which d.next.key == key, remove it; otherwise, it means it's already the end of the list, do nothing
}
}
public void rehash() {
Data[] old = map;
map = new Data[map.length * 2];
for (int i = 0; i < old.length; i++) {
Data d = old[i];
while (d != null) {
put(d.key, d.val);
d = d.next;
}
}
}
}Last updated