Can anyone help me with Leetcode LRU Cache problem?

Revision en1, by YangZhao512, 2017-01-13 11:12:44

Hope this post is not irrelevant to codeforces. I've spent lots of hours on this problem but just can't figure out what the problem is with my code. The OJ gives Runtime Error. Can anyone help me? Thanks a lot!

class LRUCache{
private:
    int cap;
    deque<int> keyList;
    map<int, deque<int>::iterator> pos;
    map<int, int> key2val;
    static const int FAIL = -1;

    void move2front(int key){
        keyList.erase(pos[key]);
        keyList.push_front(key);
        pos[key] = keyList.begin();
    }

    void evict(){
        int key = keyList.back();
        keyList.pop_back();
        pos.erase(key);
        key2val.erase(key);
    }

    void insert(int key, int val){
        keyList.push_front(key);
        key2val[key] = val;
        pos[key] = keyList.begin();
    }
public:
    LRUCache(int capacity) {
        cap = capacity;
        keyList.clear();
        pos.clear();
        key2val.clear();
    }

    int get(int key) {
        if(key2val.find(key) != key2val.end()){
            move2front(key);
            return key2val[key];
        }
        return FAIL;
    }

    void set(int key, int value) {
        if(pos.find(key) != pos.end()){
            move2front(key);
            key2val[key] = value;
        } else {
            if(keyList.size() == cap)  evict();
            insert(key, value);
        }
    }
};
Tags lru cache, leetcode

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English YangZhao512 2017-01-13 11:12:44 1473 Initial revision (published)