Map
class MyHashMap {
Integer[] values = new Integer[1000000];
/** Initialize your data structure here. */
public MyHashMap() {
}
/** value will always be positive. */
public void put(int key, int value) {
values[hash(key)] = 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) {
Integer result = values[hash(key)];
if (result == null) {
return -1;
}
return result;
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
public void remove(int key) {
values[hash(key)] = null;
}
private int hash(int value) {
return values.length % value;
// or we can use bit operator to limit number to upper boundary, which is length of array
// return hashCode & (entries.length - 1);
// hashCode: 10 , n: 9
// hashCode (in binary): 1010 , n (in binary): 1001
// position (in binary): 1000 (8 in decimal)
}
}Implementation using Entry
Last updated