146. LRU Cache

题意:

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.

思路:

设计代码的时间要详细,最好是能打好一个手稿。 设计的时间花的越久,写出的代码质量越高,边界异常越少。

这个问题是设计一个LRU。

首先一个需要存order,这个order在get的时候能很快访问到,因此需要建立一个key到order的映射。 在set和get能很快找到key对应的order。

再开一个key_value保存key对应的value。

get 分两种情况:有,没有。 set分两种:有,没有(分满,不满)。

这里需要提出来C++list还是很方便的。 只是list erase需要传入指针, map 的erase需要传入key。 

class LRUCache{
public:
    map<int,int> key_value;
    map<int, list<int>::iterator>key_ptr;
    list<int>key_order;
    int cap;
    int num;
    LRUCache(int capacity) {
        cap = capacity;
        num = 0;
    }
    
    int get(int key) 
    {
        if(key_ptr.count(key)==0)
        {
            return -1;
        }
        else 
        {
            list<int>::iterator ptr = key_ptr[key];
            key_order.erase(ptr);
            key_order.push_front(key);
            key_ptr[key] = key_order.begin();
            return key_value[key];
        }
    }
    
    void set(int key, int value) 
    {
        key_value[key] = value;
        if (key_ptr.count(key) == 0)
        {
            if(num < cap)
            {
                num++;
            }
            else 
            {
                int key_end = key_order.back();
                key_ptr.erase(key_end);
                key_order.pop_back();
            }
            key_order.push_front(key);
            key_ptr[key] = key_order.begin();
        }
        else 
        {
            list<int>::iterator ptr = key_ptr[key];
            key_order.erase(ptr);
            key_order.push_front(key);
            key_ptr[key] = key_order.begin();
        }
    }
};
View Code

 

AC代码:

 

 
posted @ 2016-03-15 22:11  Gu Feiyang  阅读(191)  评论(0)    收藏  举报