146 LRU Cache

11 篇文章 0 订阅
8 篇文章 0 订阅

1 题目

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(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.

The cache is initialized with a positive capacity.

Follow up:
Could you do both operations in O(1) time complexity?

Example:

LRUCache cache = new LRUCache( 2 /* capacity */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.put(4, 4);    // evicts key 1
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4

2 尝试解

2.1 分析

要求实现LRU,即当超过容器尺寸时,将最久没有使用到的元素删除。将每一个插入、更新和查询操作都记录唯一的时间标签,同时对时间标签和键组成的对进行排序。

使用两个数据结构,unordered_map<int,pair<int,int>> record记录键key,值val和时间标签order。map<int,int> cashe记录时间标签order,键key。每次插入、更新或者查询,全局变量时间标签order都自增一。

插入新的键值对时,将键、值、时间记入record中,将时间、键记入cashe中,同时时间标签自增一。如果容器溢出,由于cashe是红黑树,自动排序,所以(*cashe.begin()).second就是最久没有访问过的键,将其从record中删除,然后再删除cashe.begin()。复杂度为O(lg N)。

更新键key的值时,删除cashe[record[key].second],即上一个对key的操作的时间标签,将新的键、值、时间记入record中,将新的时间、键记入cashe中,同时时间标签自增一。查询操作相同。复杂度为O(lg N)。

2.2 代码

class LRUCache {
public:
    int size = 0;
    int order = 0;
    unordered_map<int,pair<int,int>> record;
    map<int,int> cashe;
    LRUCache(int capacity) {
        size = capacity;
    }
    
    int get(int key) {
        if(record.count(key)!=0){
            cashe.erase(record[key].second);
            record[key].second = order;
            cashe[order] = key;
            order += 1; 
            return record[key].first;
        }
        else return -1;
    }
    
    void put(int key, int value) {
        if(record.count(key)!=0){
            cashe.erase(record[key].second);
        }
        record[key] = make_pair(value,order);
        cashe[order] = key;
        order += 1;
        if(record.size() > size){
            int key = (*cashe.begin()).second;
            cashe.erase(cashe.begin());
            record.erase(key);
        }
    }
};

3 标准解

3.1 分析

上述解法复杂度为O(lg N)的原因在于使用map排序,map底层的红黑树插入删除复杂度均为O(lg N)。

考虑hashmap+linkedlist,用hashmap记录,用linkedlist来记录LRU,插入复杂度为O(1)。

用一个hashmap<int,int> record记录键值对,用一个hashmap<int,list<int>::iterator> order记录键和在LRU链表中的迭代器,一个list<int> LRU代表LRU。

每次插入、更新或者查询键key,都先查询order[key]判断LRU中是否存在,如果存在则删去。然后在LRU头部插入key,更新order[key] = LRU.begin(),更新键值对。

3.2 代码

class LRUCache {
public:
    int size;
    list<int> lru;                              // MRU ... LRU
    unordered_map<int, list<int>::iterator> mp; // key -> iterator
    unordered_map<int, int> kv;                 // key -> value

    LRUCache(int capacity) : size(capacity) {}
    int get(int key) {
        if (kv.count(key) == 0) return -1;
        updateLRU(key);
        return kv[key];
    }
    void put(int key, int value) {
        if (kv.size() == size && kv.count(key) == 0)
            evict();
        updateLRU(key);
        kv[key] = value;
    }
    void updateLRU(int key) {
        if (kv.count(key)) 
            lru.erase(mp[key]);
        lru.push_front(key);
        mp[key] = lru.begin();
    }
    void evict() {
        mp.erase(lru.back());
        kv.erase(lru.back());
        lru.pop_back();
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值