Why get a Runtime Error ? Last executed input: 10,[set(10,13),set(3,17),set(6,11),set(10,5),se.....]


  • -1
    W
    class LRUCache{
    public:
        unordered_map<int,int> nmap;
        vector<int> keys;
        int cap;
        LRUCache(int capacity) {
            cap = capacity;
        }
        
        int get(int key) {
            if(nmap.find(key)!=nmap.end())
               return nmap[key];
            else
               return -1;
        }
        
        void set(int key, int value) {
            if(cap == keys.size())
            {
                int lastkey = keys.back();
                keys.pop_back();
                nmap.erase(nmap.find(lastkey));
                nmap[key] = value;
                keys.insert(keys.begin(),key);
                return;
            }
            
            if(nmap.find(key)==nmap.end())
            {
                nmap[key] = value;
                keys.insert(keys.begin(),key);
            }
            else
            {
                auto iter =find(keys.begin(),keys.end(),key);
                keys.erase(iter);
                keys.insert(keys.begin(),key);
                nmap[key] = value;
            }
            
        }
    };

  • 0
    C

    in set, you should check whether key exists in nmap first, if yes, ... , else if (keys.size() < cap), ..., else {remove tail and insert at head}

    You order here is wrong


Log in to reply
 

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