题目
运用你所掌握的数据结构,设计和实现一个 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);
*/