题目:
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。
要求:在 O(1) 时间复杂度内完成这两种操作
LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 该操作会使得密钥 2 作废
cache.get(2); // 返回 -1 (未找到)
cache.put(4, 4); // 该操作会使得密钥 1 作废
cache.get(1); // 返回 -1 (未找到)
cache.get(3); // 返回 3
cache.get(4); // 返回 4
这一题,考到了我薄弱的地方,对于hash表不太熟;
不过这一题其实对于数据结构的掌握要很熟悉;别人给的解法就是hash表加双向链表;
我觉得最关键的地方就是在于每一次对于put进的key-value,都放在链表的尾部,而当超过容量时,就删除头部用的次数最少的key-value;其思想就是每一次访问的key-value(无论时put还是get),都放在链表的尾部(表示最近使用过的数据),对于put进的数据,如果超过容量的话,就删除链表的头部,表示最近使用次数最少,那么就删除也就是最近最少使用算法;
首先对于put还是get,都需要查询缓存中是否存在,这要求时间是O(1),那么就需要使用hash表,但是当超过容量时,此时要把最少使用的删除,即找到这个最少使用的,也是O(1)时间,从而需要单独的数据结构取维护,因此使用链表,每一次访问的放队尾,要删除时就删除队首,而队首正好是使用时间最少的。而链表的删除也是O(1),
首先,链表可以进行O(1)时间进行插入和删除操作,但是查找却是线性的,所以这里就要求要用辅助结构来进行查找此节点;
于是就用到了hash表,value存链表的节点,这样查找时间就变成了O(1)时间;
为什么要用双向链表呢,单向链表无法直接定位队尾的节点,它只能定为队首,从而就不能维护我想要的直接删除队首和直接插入队尾了
class LRUCache {
public:
int size=0;
unordered_map<int, list<pair<int, int>>::iterator> key_set;//存储链表节点所在位置
list<pair<int, int>> node;
LRUCache(int capacity) {
size=capacity;
}
int get(int key) {
auto temp=key_set.find(key);
//未找到,直接返回
if(temp==key_set.end()) return -1;
else{
//再次访问,表示最近使用了,插至队尾
int k=temp->first;
int var=temp->second->second;
node.erase(temp->second);
key_set.erase(temp);
node.push_back(pair<int,int>(k,var));
key_set.insert(pair<int,list<pair<int, int>>::iterator >(k, --node.end()));
return var;
}
}
void put(int key, int value) {
auto temp=key_set.find(key);
if(temp==key_set.end()){
//若没有,则插入,但要检查容量
if(node.size()==size){
//超过容量,就删除最近最少使用的队首
key_set.erase(node.begin()->first);
node.erase(node.begin());
}
//将新访问,插入队尾
node.push_back(pair<int,int>(key,value));
key_set.insert(pair<int,list<pair<int, int>>::iterator>(key,--node.end()));
}
else{
//再次访问,表示最近又访问了,插入队尾
node.erase(temp->second);
key_set.erase(temp);
node.push_back(pair<int,int>(key,value));
key_set.insert(pair<int,list<pair<int, int>>::iterator>(key,--node.end()));
}
}
};