Cannot get rid of runtime error with the following code


  • 0
    H
    class LRUCache{
    public:
        int currcap, maxcap;
        list<pair<int, int>> cache;
        unordered_map<int, list<pair<int, int>>::iterator> hasht;
    
        LRUCache(int capacity) {
            currcap=0;
            maxcap=capacity;
        }
        
        void promote(int key, int val)
        {
            cache.erase(hasht[key]);
            pair<int, int> tmp;
            tmp.first=key;
            tmp.second=val;
            cache.push_front(tmp);
            hasht[key]=cache.begin();
        }
        
        void insert(int key, int value)
        {
            pair<int, int> tmp;
            tmp.first=key;
            tmp.second=value;
            cache.push_front(tmp);
            hasht[key]=cache.begin();
        }
        
        int get(int key) {
            if(hasht.find(key)!=hasht.end())
            {
                int val=(*hasht[key]).second;
                promote(key, val);
                return val;
            }
            
            return -1;
        }
        
        void set(int key, int value) {
            if(hasht.find(key)!=hasht.end())
            {
                promote(key, value);
            }
            else if(currcap<maxcap)
            {
                insert(key, value);
                currcap++;
            }
            else
            {
                hasht.erase(key);
                cache.pop_back();
                insert(key, value);
            }
        }
    };

  • 0
    H

    try to use this test case:
    2,[set(2,1),set(1,1),get(2),set(4,1),get(1),get(2)]
    Output: your output
    Expected: [1,-1,1]


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.