Leetcode -- LRU Cache

来源:互联网 发布:1978年中国经济数据 编辑:程序博客网 时间:2024/05/12 14:12

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.

分析:

这是一个要求设计数据结构的题目,设计的要求是既能快速查找,又能方便移动,因此比较合适的方案是结合链表和哈希表。

在实现时,利用了STL中的list和map,让map指向list中的iterator,从而弥补list不能随机访问的缺点。

struct node{    int val;    list<int>::iterator iter;    node(int v,list<int>::iterator it)    {        val = v;        iter = it;    }};class LRUCache{public:    void move2end(int key)    {        list<int>::iterator it = mp[key]->iter;        l.erase(it);        l.push_back(key);        mp[key]->iter = --l.end();    }        LRUCache(int capacity) {        this->capacity = capacity;    }        int get(int key) {        if(mp.find(key)!=mp.end())        {            move2end(key);            return mp[key]->val;        }        else return -1;    }        void set(int key, int value) {        if(mp.find(key)!=mp.end())        {            move2end(key);            mp[key]->val = value;        }        else if(mp.size()<capacity)        {            l.push_back(key);            mp[key]=new node(value,--l.end());        }        else        {            int tmp = l.front();            l.pop_front();            mp.erase(tmp);            l.push_back(key);            mp[key]=new node(value,--l.end());        }    }    map<int,node*> mp;    list<int> l;    int capacity;};


0 0