Closed congr closed 5 years ago
class MyHashMap {
int BUCKET_SIZE = 512;
ArrayList[] bucket;
class Pair {
int k, v;
Pair(int k, int v) {
this.k = k; this.v = v;
}
}
/** Initialize your data structure here. */
public MyHashMap() {
bucket = new ArrayList[BUCKET_SIZE];
for (int i = 0; i < BUCKET_SIZE; i++)
bucket[i] = new ArrayList();
}
/** value will always be non-negative. */
public void put(int key, int value) {
ArrayList<Pair> list = bucket[hash(key)];
for (Pair p : list) {
if (p.k == key) {
p.v = value;
return;
}
}
list.add(new Pair(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) {
ArrayList<Pair> list = bucket[hash(key)];
for (Pair p : list)
if (p.k == key) return p.v;
return -1;
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
public void remove(int key) {
ArrayList<Pair> list = bucket[hash(key)];
for (Pair p : list) {
if (p.k == key) {
list.remove(p);
return;
}
}
}
int hash(int key) {
return key % BUCKET_SIZE;
}
}
/**
* 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);
*/
https://leetcode.com/problems/design-hashmap/