首页 > 其他 > 详细

leetcode-LRU

时间:2014-12-01 22:05:33      阅读:210      评论:0      收藏:0      [点我收藏+]
class LRUCache{
public:
struct node
{
    int key;
    int value;
    node(int k,int v):key(k),value(v){}
};
    LRUCache(int capacity1) {
        capacity = capacity1;
    }
    
    int get(int key) {
            unordered_map<int, node *>::iterator it = pos.find(key);
    if(it == pos.end())
        return -1;
    node * check = it->second;
    int result = check->value;
    linked.remove(check);
    linked.push_front(check);
    }
    
    void set(int key, int value) {
        unordered_map<int, node *>::iterator it = pos.find(key);

    if(it != pos.end())
    {
        node *t = it->second;
        t->value = value;
        linked.remove(t);
        linked.push_front(t);
    }
    else
    {
        node *t = new node(key, value);
        pos.insert(make_pair(key, t));
        if(linked.size() < capacity)
        {
            linked.push_front(t);
        }
        else
        {
            node *temp = linked.back();
            linked.pop_back();
            linked.push_front(t);
            pos.erase(temp->key);
            delete temp;
        }
    }
    }
    
    private:
    int capacity;
    unordered_map<int, node *> pos;
    list<node *> linked;
};

 

leetcode-LRU

原文:http://www.cnblogs.com/ouchengeng/p/4135984.html

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