146. LRU Cache hash+链表

来源:互联网 发布:网络运营商排行榜 编辑:程序博客网 时间:2024/05/12 23:18

题目地址

使用了一个hash表和一个链表,每次访问元素(get)或是添加元素都将元素置于链表的头部,尾部的自然就是最久未使用的。
hash表存储元素在链表中的位置,链表储存key-value,以方便超出容量时从hash表移除旧元素。

class LRUCache {public:    unordered_map<int, list<pair<int, int>>::iterator> ump;    list<pair<int, int>> values;    int size;    LRUCache(int capacity) {        size = capacity;    }    int get(int key) {        if (ump.count(key)) {            auto now = *ump[key];            int value = now.second;            values.erase(ump[key]);            values.push_front(now);            ump[key] = values.begin();            return value;        }        return -1;    }    void put(int key, int value) {        if (ump.count(key)) {            values.erase(ump[key]);        }        values.push_front(make_pair(key, value));        ump[key] = values.begin();        if (values.size() > size) {            pair<int, int> end = (pair<int, int> &&) values.back();            ump.erase(end.first);            values.pop_back();        }    }};/** * 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); */
0 0