码迷,mamicode.com
首页 > 系统相关 > 详细

LRU Cache -- leetcode

时间:2015-06-07 11:10:42      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:lru   leetcode   

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

标签:lru   leetcode   

原文地址:http://blog.csdn.net/elton_xiao/article/details/46398353

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!