I am trying to create an LRU cache using a LinkedHashMap and the iterator. It works for many of the test cases. But for some of the large test cases, it produces a few incorrect outputs for the get().
To me, the code makes perfect sense. Perhaps, I missing something or maybe my understanding of the linkedHashMap is incomplete.
Could anyone find the bug in the implementation? Unfortunately, I cannot post the test case as it is too large. You can try to run this code on https://leetcode.com/problems/lru-cache/.
class LRUCache {
private LinkedHashMap<Integer, Integer> map;
private int maxCap;
public LRUCache(int capacity) {
this.map = new LinkedHashMap<>();
this.maxCap = capacity;
}
public int get(int key) {
if (map.containsKey(key)) {
int val = map.get(key);
map.remove(key);
map.put(key, val);
return val;
}
return -1;
}
public void put(int key, int value) {
if (maxCap == map.size()) {
Integer val = map.get(key);
if (val != null) {
map.remove(key);
} else {
Iterator<Integer> itr = map.keySet().iterator();
if (itr.hasNext()) {
itr.next();
itr.remove();
}
}
}
map.put(key, value);
}
}