LRU Cache -- leetcode

本文介绍了一种基于链表和哈希表实现的LRU(Least Recently Used)缓存机制。该机制支持get和set操作,并能在缓存达到容量限制时移除最近最少使用的元素。通过使用链表和哈希表,保证了高效的访问和更新速度。

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.


基本思路:

用一个map处理查找问题。

用list维护按使用元素排序。将近期被訪问的记录,总是移动到链表头。

list中存储的是[key, value],

而map中存储的是key, 以及在list中相应节点的iterator。  


在将list中的元素移动到最前时,使用了splice函数。 此函数比先删除,再插入,要高效。


此代码在leetcode上实际运行时间为160ms。

class LRUCache{
public:
    LRUCache(int capacity) :capacity_(capacity) {
        
    }
    
    int get(int key) {
        auto iter = cache_.find(key);
        if (iter == cache_.end())
            return -1;
        
        lru_.splice(lru_.begin(), lru_, iter->second);
        return iter->second->second;
    }
    
    void set(int key, int value) {
        if (get(key) != -1) {
            lru_.front().second = value;
            return;
        }
        
        if (lru_.size() == capacity_) {
            cache_.erase(lru_.back().first);
            lru_.pop_back();
        }
        
        lru_.push_front(make_pair(key, value));
        cache_[key] = lru_.begin();
    }
private:
    typedef list<pair<int, int> > list_t;
    typedef unordered_map<int, list_t::iterator> map_t;
    list_t lru_;
    map_t cache_;
    const int capacity_;
};


版权声明:本文博主原创文章。博客,未经同意不得转载。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值