首页 > 系统服务 > 详细

LRU Cache

时间:2017-02-15 23:28:49      阅读:228      评论:0      收藏:0      [点我收藏+]

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.

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

分析: 一个比较好的设计数据结构的例子, 使用unordered_map 和list 容器, list 存放最近查询的节点 很巧妙的是map 中存放<int, list<pair<int, int>>::iterator> list中存放 list<pair<int, int>>, 这样两者互相访问都是O(1)

class LRUCache {
public:
    LRUCache(int capacity):_capacity(capacity) {
    }
    
    int get(int key) {
        auto iter =  Cache_Map.find(key);
        if(iter == Cache_Map.end())
            return -1;
        int value = iter->second->second;
        Cache_List.splice(Cache_List.begin(),Cache_List, iter->second);
        return value;
    }
    
    void put(int key, int value) {
        auto iter = Cache_Map.find(key);
        if(iter != Cache_Map.end()){
            iter->second->second = value;
            Cache_List.splice(Cache_List.begin(),Cache_List, iter->second);
            return;
        }
        if(Cache_Map.size() == _capacity){
            int del = Cache_List.back().first;
            cout << "delete "<< del << endl;
            Cache_List.pop_back();
            Cache_Map.erase(del);
        }
        Cache_List.emplace_front(key,value);
        // cout << "print the map"<<endl;
        // for(auto it = Cache_Map.begin(); it!=Cache_Map.end(); it++)
        //     cout << it->first << " -> "<< it->second->second<<endl;
        // cout << "print the list"<<endl;
        // for(auto it = Cache_List.begin(); it!=Cache_List.end(); it++)
        //     cout << it->first << " -> "<< it->second<<endl;
        Cache_Map[key] = Cache_List.begin();
        
       
    }
    
private:
    int _capacity;
    unordered_map<int, list<pair<int, int>>::iterator> Cache_Map;
    list<pair<int, int>> Cache_List;
    
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */

 

LRU Cache

原文:http://www.cnblogs.com/willwu/p/6403779.html

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