Created
May 27, 2020 14:22
-
-
Save RehmanaliMomin/0cf7e5e2e56a8ee9fbfffccea5125dfc to your computer and use it in GitHub Desktop.
Implementing LRU cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LRUCache { | |
int capacity; | |
HashMap<Integer,Integer> map; | |
LinkedList<Integer> queue; | |
public LRUCache(int capacity) { | |
this.capacity = capacity; | |
map = new HashMap<>(); | |
queue = new LinkedList<>(); | |
} | |
public int get(int key) { | |
if(map.containsKey(key)) { | |
queue.remove(new Integer(key)); | |
queue.addFirst(key); | |
return map.get(key); | |
} | |
return -1; | |
} | |
public void put(int key, int value) { | |
if(map.containsKey(key)){ | |
queue.remove(new Integer(key)); | |
queue.addFirst(new Integer(key)); | |
map.replace(key,value); | |
}else{ | |
if(queue.size()==capacity) { | |
map.remove(queue.pollLast()); | |
queue.addFirst(key); | |
map.put(key,value); | |
} | |
else{ | |
queue.addFirst(key); | |
map.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); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment