首页 > 代码库 > leetcode-LRU

leetcode-LRU

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 =http://www.mamicode.com/ 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