zoukankan      html  css  js  c++  java
  • LRU Cache -- 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_;
    };


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

  • 相关阅读:
    bzoj3211 花神游历各国
    bzoj1010
    day8
    day6&7
    bzoj1087
    noi同步赛day1
    bzoj1076
    day3&4&5
    bzoj1079 dp
    cholesky分解
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/4877903.html
Copyright © 2011-2022 走看看