Solution: Array + LinkedList
This only supports Integer as key
class MyHashMap {
private class Pair {
private int key;
private int value;
public Pair(int key, int value) {
this.key = key;
this.value = value;
}
public int getKey() {
return this.key;
}
public int getValue() {
return this.value;
}
public void setValue(int value) {
this.value = value;
}
}
private LinkedList[] buckets;
private static final int BASE = 769; // chose a prime number as bucket size
public MyHashMap() {
buckets = new LinkedList[BASE];
for (int i = 0; i < BASE; i++) {
buckets[i] = new LinkedList<Pair>();
}
}
private int hash(int key) {
return key % BASE;
}
public void put(int key, int value) {
int h = hash(key);
Iterator<Pair> it = buckets[h].iterator();
while (it.hasNext()) {
Pair p = it.next();
if (p.getKey() == key) {
p.setValue(value);
return;
}
}
buckets[h].offer(new Pair(key, value));
}
public int get(int key) {
int h = hash(key);
Iterator<Pair> it = buckets[h].iterator();
while (it.hasNext()) {
Pair p = it.next();
if (p.getKey() == key) {
return p.getValue();
}
}
return -1;
}
public void remove(int key) {
int h = hash(key);
Iterator<Pair> it = buckets[h].iterator();
while(it.hasNext()) {
Pair p = it.next();
if (p.getKey() == key) {
buckets[h].remove(p);
return; // !!!
}
}
}
}
To support string as key
- In Java,
String.hashCode()method would probably return a negative int. IfhashCodeis negative, this can result in a negative index. key.hashCode() & 0x7fffffffmakes sure it's non negative-
The prefix
0xmeans “this number is in hex”. -
7FFFFFFFis a hex number representing a 32-bit integer. Which is the biggest positive integer in Java. ( 0111 1111 1111 1111 1111 1111 1111 1111) -
IF the binay representation of an int's first digit is 1, means it's an negative int
-
private int hash(String key) {
return (key.hashCode() & 0x7fffffff) % BASE;
}