1.
2.
class LRUCache {
private HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
private LinkedList<Integer> linkedList = new LinkedList<Integer>();
private int capacity;
private int len;
public LRUCache(int capacity) {
this.capacity = capacity;
len = 0;
}
public int get(int key) {
if (map.containsKey(key)) {
linkedList.remove((Integer)key);
linkedList.offerFirst((Integer)key);
return map.get(key);
} else {
return -1;
}
}
public void put(int key, int value) {
if (map.containsKey(key)) {
map.put(key, value);
linkedList.remove((Integer)key);
linkedList.offerFirst((Integer)key);
} else {
if (len < capacity) {
linkedList.offerFirst((Integer)key);
map.put(key, value);
len++;
} else {
Integer lastKey = linkedList.pollLast();
linkedList.offerFirst((Integer)key);
map.remove(lastKey);
map.put(key, value);
}
}
}
}