首页 > 系统服务 > 详细

LRU Cache -- leetcode

时间:2015-10-14 17:26:20      阅读:199      评论:0      收藏:0      [点我收藏+]

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_;
};


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

LRU Cache -- leetcode

原文:http://www.cnblogs.com/gcczhongduan/p/4877903.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!