LRU Cache

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);
 */

 

posted @ 2017-02-15 22:51  WillWu  阅读(212)  评论(0编辑  收藏  举报