Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
public class LRUCache {
private LinkedList<Integer> list;
private Map<Integer, Integer> map;
private int size;
public LRUCache(int capacity) {
list = new LinkedList<Integer>();
map = new HashMap<Integer, Integer>();
size = capacity;
}
public int get(int key) {
Integer e = key;
if (map.containsKey(e)) {
list.remove(e);
list.addFirst(e);
return map.get(e);
} else {
return -1;
}
}
public void set(int key, int value) {
Integer e = key;
if (!map.containsKey(e)) {
list.addFirst(e);
map.put(key, value);
if (list.size() > size) {
Integer last = list.removeLast();
map.remove(last);
}
} else {
map.put(key, value);
list.remove(e);
list.addFirst(e);
}
}
}