I am trying to solve the LeetCode problem 146. LRU Cache:
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 thekey
if thekey
exists, otherwise return -1.void put(int key, int value)
Update the value of thekey
if thekey
exists. Otherwise, add thekey-value
pair to the cache. If the number of keys exceeds thecapacity
from this operation, evict the least recently used key.The functions
get
andput
must each run in O(1) average time complexity.
This is my code:
class LRUCache {
Stack<Integer> stack;
HashMap<Integer, Integer> cache;
int capacity;
public LRUCache(int capacity) {
this.capacity = capacity;
stack = new Stack<>();
cache = new HashMap<>();
}
public int get(int key) {
if(!cache.containsKey(key)) return -1;
else
stack.removeElement(key);
stack.push(key);
return cache.get(key);
}
public void put(int key, int value) {
if(cache.containsKey(key)){
stack.removeElement(key);
}
else if(stack.size() == capacity){
int leastRecent = stack.remove(0);
cache.remove(leastRecent);
}
stack.push(key);
cache.put(key, value);
}
}
/*
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/
All the test cases passed but I am getting "time limit exceeded" error:
How can I improve the efficiency of my code?