題目
運用你所掌握的數據結構,設計和實現一個 LRU (最近最少使用) 緩存機制。它應該支持以下操作: 獲取數據 get 和 寫入數據 put 。
獲取數據 get(key) - 如果密鑰 (key) 存在於緩存中,則獲取密鑰的值(總是正數),否則返回 -1。
寫入數據 put(key, value) - 如果密鑰已經存在,則變更其數據值;如果密鑰不存在,則插入該組「密鑰/數據值」。當緩存容量達到上限時,它應該在寫入新數據之前刪除最久未使用的數據值,從而爲新的數據值留出空間。
算法
使用時間戳動態地更新每個key的最新使用時間,雖然有一定的侷限性,但是不失爲一種方法。
三個map
1. <key,value>
2. <timestampId,key>
3. <key,timestampId>
代碼
class LRUCache {
long idx;
int cap;
TreeMap<Long,Integer> idTok;
Map<Integer,Long> kToid;
Map<Integer,Integer> kv;
public LRUCache(int capacity) {
cap=capacity;
idx=0;
kToid=new HashMap<>();
kv=new HashMap<>();
idTok=new TreeMap<>();
}
public void update(int key){
if(kv.containsKey(key)){
long oid=kToid.get(key);
idTok.remove(oid);
}
idTok.put(idx,key);
kToid.put(key,idx);
idx++;
}
public int get(int key) {
if(!kv.containsKey(key)) return -1;
int res=kv.get(key);
update(key);
return res;
}
public void put(int key, int value) {
if(kv.size()>=cap&&!kv.containsKey(key)){
long oid=idTok.firstKey();
int oldk=idTok.get(oid);
kv.remove(oldk);
kToid.remove(oldk);
idTok.remove(oid);
}
update(key);
kv.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);
*/