问题描述
运用你所掌握的数据结构,设计和实现一个 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
思路
分析上面的操作过程,要让 put 和 get 方法的时间复杂度为$ O(1)$,我们可以总结出 cache 这个数据结构必要的条件:查找快,插入快,删除快,有顺序之分。
因为显然 cache 必须有顺序之分,以区分最近使用的和久未使用的数据;而且我们要在 cache 中查找键是否已存在;如果容量满了要删除最后一个数据;每次访问还要把数据插入到队头。
那么,什么数据结构同时符合上述条件呢?哈希表查找快,但是数据无固定顺序;链表有顺序之分,插入删除快,但是查找慢。所以结合一下,形成一种新的数据结构:哈希链表。
LRU
缓存算法的核心数据结构就是哈希链表,双向链表和哈希表的结合体。这个数据结构长这样:
思想很简单,就是借助哈希表赋予了链表快速查找的特性嘛:可以快速查找某个 key 是否存在缓存(链表)中,同时可以快速删除、添加节点。回想刚才的例子,这种数据结构是不是完美解决了 LRU 缓存的需求?
也许读者会问,为什么要是双向链表,单链表行不行?另外,既然哈希表中已经存了 key,为什么链表中还要存键值对呢,只存值不就行了?
想的时候都是问题,只有做的时候才有答案。这样设计的原因,必须等我们亲自实现 LRU 算法之后才能理解,所以我们开始看代码吧~
利用链表和哈希表的映射,达到高速缓存的作用;这里面设计建模,详情请看LRU建模解析
CPP
class LRUCache {
private:
int _cap;
// 双链表:装着 (key, value) 元组
list<pair<int, int>> cache;
// 哈希表:key 映射到 (key, value) 在 cache 中的位置
unordered_map<int, list<pair<int, int>>::iterator> umap;
public:
LRUCache(int capacity) {
_cap = capacity;
}
int get(int key) {
auto iter = umap.find(key);
if(iter == umap.end())return -1;
pair<int,int> kv = *umap[key];
cache.erase(umap[key]);//改
cache.push_front(kv);
umap[key] = cache.begin();
return kv.second;
}
void put(int key, int value) {
auto iter = umap.find(key);
if(iter != umap.end()){ //存在于缓存
cache.erase(umap[key]);
cache.push_front(make_pair(key,value));
umap[key] = cache.begin();
return;
}
//不在缓存中
if(cache.size() == _cap) //满了
{
auto iter = cache.back();
umap.erase(iter.first);
cache.pop_back();
cache.push_front(make_pair(key,value));
umap[key] = cache.begin();
}
else //没满
{
cache.push_front(make_pair(key,value));
umap[key] = cache.begin();
}
}
};
GO
type list struct{ //双向链表,用于保存key:value
prev,next *list
key,val int
}
type LRUCache struct {
_len,_cap int
front,back *list //头尾指针
umap map[int]*list //hash表
}
func Constructor(capacity int) LRUCache {
return LRUCache{
_len : 0,
_cap : capacity,
front: nil,
back : nil,
umap : make(map[int]*list,capacity),
}
}
func (this *LRUCache) Get(key int) int {
if node,ok := this.umap[key];ok{ //存在
this.push_front(node)
return node.val
}
return -1
}
func (this *LRUCache) Put(key int, value int) {
if node,ok := this.umap[key];ok{
node.val = value
this.push_front(node)
return
}
//找不到
if this._len == this._cap{
delete(this.umap,this.back.key)
this.pop_back()
}else{
this._len++
}
node := &list{
prev:nil,
next:nil,
key:key,
val:value,
}
this.umap[key] = node
this.insert_front(node)
}
func (this *LRUCache) push_front(node *list){
switch node{ //先删除,再插入
case this.front:
return
case this.back:
this.pop_back()
default:
node.prev.next = node.next
node.next.prev = node.prev
}
this.insert_front(node)
}
func (this *LRUCache) pop_back(){
if this.back.prev != nil{ //链表长度大于1
this.back.prev.next = nil
}else{ //链表长度小于等于1
this.front = nil
}
this.back = this.back.prev
}
func (this *LRUCache)insert_front(node *list){
if this.back == nil{
//空表
this.back = node
}else{ //头插法
node.next = this.front
this.front.prev = node
}
this.front = node
}
/**
* Your LRUCache object will be instantiated and called as such:
* obj := Constructor(capacity);
* param_1 := obj.Get(key);
* obj.Put(key,value);
*/
我自己写的,用的是普通列表,寻找时间是 O ( n ) O(n) O(n),可以通过,但是很慢
class LRUCache {
public:
LRUCache(int capacity) {
_cap = capacity;
_sz = 0;
}
int get(int key) {
auto iter = umap.find(key);
if(iter == umap.end())return -1;
lst.remove(key);
lst.push_front(key);
return iter->second;
}
void put(int key, int value) {
auto iter = umap.find(key);
if(iter != umap.end()){
umap[key] = value;
lst.remove(key);
lst.push_front(key);
}
else if(_sz == _cap)
{
auto iter = umap.find(lst.back());
umap.erase(iter);
umap[key] = value;
lst.pop_back();
lst.push_front(key);
}
else
{
_sz++;
umap[key] = value;
lst.push_front(key);
}
}
private:
unordered_map<int,int> umap;//key,value
list<int> lst;//最新排名
int _cap;
int _sz;
};
/**
* 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);
*/