您的位置:首页 > 其它

leetcode LRU Cache

2014-04-13 17:04 323 查看
题目大意就是使用最近最少使用算法(LRU)来实现一个读取和写入值的数据结构。主要注意点在于链表和map的使用,map插入和寻找数据的操作都是O(logn),可以帮助迅速定位链表中的位置。每次读取数据时,都要将链表的该节点移到链表的前端,并修改map中的value值,当需要插入数据且链表满的时候,删除链表的最后一个数据,删除map中的对应的key,最后在链表前端插入数据,然后map存储对应位置信息。

#include <list>
#include <iostream>
#include <map>
using namespace std;
class Key
{
public:
int key,value;
Key():key(0),value(0){};
Key(int key, int value):key(key),value(value){};
};
class LRUCache{
private:
int size;
int capacity;
list<Key> cache;
map< int, list<Key>::iterator > search;
public:
LRUCache(int capacity)
{
size = 0;
this->capacity = capacity;
}
int get(int key)
{
map<int, list<Key>::iterator>::iterator it = search.find(key);
if(it != search.end())
{
int value = it->second->value;
cache.erase(it->second);
cache.insert(cache.begin(),Key(key, value));
it->second = cache.begin();
return value;
}
return -1;
}
void set(int key, int value)
{
map<int, list<Key>::iterator>::iterator it = search.find(key);
if(it != search.end())
{
cache.erase(it->second);
cache.insert(cache.begin(), Key(key, value));
it->second = cache.begin();
return;
}
else
{
if(size < capacity)
{
size++;
cache.insert(cache.begin(), Key(key, value));
search.insert(map<int, list<Key>::iterator>::
value_type(key, cache.begin()));
}
else
{
search.erase(cache.rbegin()->key);
cache.pop_back();
cache.insert(cache.begin(), Key(key, value));
search.insert(map<int, list<Key>::iterator>::
value_type(key, cache.begin()));
}
}
}
};

int main()
{

LRUCache lru(1);
lru.set(2, 1);
cout << lru.get(2) << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: