Q:
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and set
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value)
- Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
首先我们要了解什么是LRU算法? LRU是Least Recently Used的缩写,即最少使用页面置换算法,是为虚拟页式存储管理服务的。通俗点说就是当内存满了之后将最近最少使用的数据丢掉,这样现在来的数据就能放进内存。
Cache(高速缓存), 一个在计算机中几乎随时接触的概念。CPU中Cache能极大提高存取数据和指令的时间,让整个存储器(Cache+内存)既有Cache的高速度,又能有内存的大容量;操作系统中的内存page中使用的Cache能使得频繁读取的内存磁盘文件较少的被置换出内存,从而提高访问速度;数据库中数据查询也用到Cache来提高效率;即便是Powerbuilder的DataWindow数据处理也用到了Cache的类似设计。Cache的算法设计常见的有FIFO(first in first out)和LRU(least recently used)。根据题目的要求,显然是要设计一个LRU的Cache。
该题的要求是设计一个数据结构,需要有两个方法:get(), set()。get()顾名思义,set()要注意的是当初始给定的大小满了时,这个时候就需要将最近最少使用的节点删除,新的节点再放进去。
网上有很多解法,比如双链表解法,但是这种我自己实现了之后超时,于是采用map来做。
因为map在插入节点的时候会根据key的值自动排序,所以我们可以利用这点,设计一个map,以count(使用度或者可以说优先级)和key为键值对,根据count排序,当空间满了之后只要将最后一个即count最小的节点删掉,将新的节点加进去就行,而且每次get()之后就要将get的节点的count值更新,应该是将它放到头部,新加入的节点也放在头部,这些我们都用一个成员变量count来控制。
代码:
struct node {
int value, count; //count为该节点的使用情况,count越大使用越频繁
node(int v, int c) : value(v), count(c) {}
};
class LRUCache{//a way to improve effeiciency is to use list rather than map to store count numbers. and use hashtable
public:
int count, cap, sz; //count为成员变量,后来的节点的count值初始就比前面的count大
map<int, int> ck; //count, key 插入一个新节点时会根据count排序,容量不够时把begin()删除即可,后插入的节点count比前面插入的要大
//因为map中是根据'键'来排序,所以该map中只能是count - key键值对, 如果要删除必须根据count删除,此时就需要根据kv中key来获得node的count拷贝
map<int, node> kv; //key, node<value, count>
LRUCache(int capacity) : count(0x80000000), cap(capacity), sz(0){
}
int get(int key) {
if(cap <= 0)
return -1;
map<int, node>::iterator p = kv.find(key);
if(p != kv.end()) {
++count;
ck.erase(p->second.count); //根据p的count值将ck中的count记录删掉,以便后面可以重新在ck中插入新的count,key键值对,下面同理
p->second.count = count;
ck.insert(pair<int, int>(count, key));
return p->second.value;
} else {
return -1;
}
}
void set(int key, int value) {
if(cap <= 0)
return;
++count;
map<int, node>::iterator p = kv.find(key);
if(p != kv.end()) {
ck.erase(p->second.count);
p->second.count = count;
ck.insert(pair<int, int>(count, key));
p->second.value = value;
} else {
if(sz < cap) {
kv.insert(pair<int, node>(key, node(value, count)));
ck.insert(pair<int, int>(count ,key));
++sz;
} else {
int tmpKey = ck.begin()->second; //key
kv.erase(tmpKey);
ck.erase(ck.begin());
kv.insert(pair<int, node>(key, node(value, count)));
ck.insert(pair<int, int>(count ,key));
}
}
}
};