I am solving leetcode LRU design problem - Leetcode LRU:
Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
Implement the LRUCache class:
LRUCache(int capacity)Initialize the LRU cache with positive sizecapacity.int get(int key)Return the value of thekeyif thekeyexists, otherwise return -1.void put(int key, int value)Update the value of thekeyif thekeyexists. Otherwise, add thekey-valuepair to the cache. If the number of keys exceeds thecapacityfrom this operation, evict the least recently used key.The functions
getandputmust each run in O(1) average time complexity.
I designed it with using Queue and HashMap, and I was able to pass 20 out of 22 test cases. However, the remaining test cases are timing out.
On searching, I found that a doubly linked list is the best way to implement it. I am curious as why queue and hash map is timing out and why a doubly linked list is the best way to solve this.
Below is my implementation:
class LRUCache {
int capacity=0;
BlockingQueue<Integer> queue;
Map<Integer, Integer> map = new HashMap<>();
public LRUCache(int capacity) {
this.capacity = capacity;
queue = new ArrayBlockingQueue<Integer>(capacity);
}
public int get(int key) {
if(queue.contains(key)){
queue.remove(key);
queue.add(key);
return map.get(key);
}
else
return -1;
}
public void put(int key, int value) {
if(queue.contains(key)){
queue.remove(key);
queue.add(key);
map.put(key, value);
}
else if(queue.size()<capacity){
queue.add(key);
map.put(key,value);
}
else{
int oldKey = queue.remove();
map.remove(oldKey);
queue.add(key);
map.put(key,value);
}
}
}
The result is as shown below:

queue.remove(key)andqueue.contains(key)?getandputmust each run in O(1) average time complexity."