【leetcode】146.(Hard)LRU Cache
阿新 • • 發佈:2018-12-27
解題思路:
用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);
}
}
}
執行結果: