LRU Cache

来源:互联网 发布:mysql多表查询面试题 编辑:程序博客网 时间:2024/05/03 15:49

Description:

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最终要的就是要给每次操作打一个时间戳,淘汰的时候保证优先淘汰时间戳最小的。实现方法有两种,第一种就是通过一个计数器来实现时间戳,每次操作时计数器都加一,包括get,set 和insert。每次淘汰时先淘汰计数器最小的。这个方法的缺点是需要遍历才能找到计数器最小的,比较慢。而且会存在计数器溢出的情况。

第二种方法是用双向链表来实现,每次操作时把被操作的节点放到整个list的开头,这样在淘汰时只要淘汰list的最后一个节点即可。因为时间戳的顺序就是list的顺序。这种方法是最优的,速度很快。下面是实现的第一种方法。

Solution:

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class LRUCache{
public:
map<int,pair<int,int> > cache;
int c;
long long cnt;
LRUCache(int capacity) : c(capacity),cnt(0){

}

int get(int key) {
if(c==0)return -1;
if(cache.find(key)==cache.end())return -1;
cache[key].second=cnt++;
return cache[key].first;
}

void set(int key, int value) {
if(c==0)return;
if(cache.find(key)!=cache.end())
{
cache[key].second=cnt++;
cache[key].first=value;
return;
}
if(cache.size()<c)
{
cache.insert(make_pair(key,make_pair(value,cnt++)));
return;
}
map<int,pair<int,int> >::iterator it=cache.begin(),deleted=cache.begin();
int tmin=(*it).second.second;
while(it!=cache.end())
{
if((*it).second.second<tmin)
{
tmin=(*it).second.second;
deleted=it;
}
++it;
}
cache.erase(deleted);
cache.insert(make_pair(key,make_pair(value,cnt++)));
return;
}
};

0 0
原创粉丝点击