码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-LRU

时间:2014-12-01 22:05:39      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   sp   on   div   log   bs   

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

标签:style   blog   color   os   sp   on   div   log   bs   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!