解题思路:
用map来记录数据
用list数组更新数据的使用情况
提交代码:
class LRUCache {
Map<Integer,Integer> map=new HashMap<>();
List<Integer> history=new ArrayList<>();
int cap;
public LRUCache(int capacity) {
this.cap=capacity;
}
public int get(int key) {
if(!map.containsKey(key)) return -1;
history.remove((Integer)key);
history.add(key);
return map.get((Integer)key);
}
public void put(int key, int value) {
if(map.containsKey(key)) {
map.put(key, value);
history.remove((Integer)key);
history.add(key);
}
else if(history.size()==cap) {
int p=history.remove(0);
map.remove(p);
history.add(key);
map.put(key, value);
}else {
history.add(key);
map.put(key, value);
}
}
}
运行结果: