G++ passed, but OJ has a Runtime Error


  • 0
    N

    https://oj.leetcode.com/submissions/detail/9364213/

    This is my code:

    typedef std::pair<int, int> KV;
    typedef std::list<KV>::iterator ITER;
    
    class LRUCache{
    private:
        int cap;
        std::unordered_map<int, ITER> myCache;
        std::list<KV> seq;
        
    public:
        LRUCache(int capacity) {
            cap = capacity;
        }
        
        int get(int key) {
            auto it = myCache.find(key);
            if(it != myCache.end()) {
                int val = (it->second)->second;
                seq.splice(seq.begin(), seq, it->second);
                return val;
            } else {
                return -1;
            }
        }
        
        void set(int key, int value) {
            auto it = myCache.find(key);
            // found, update
            if(it != myCache.end()) {
                seq.splice(seq.begin(), seq, it->second);
            } else {
                // not found, exceed cap
                if(myCache.size() >= cap) {
                    seq.pop_back();
                    seq.push_front(KV(key, value));
                    myCache.erase(key);
                    myCache[key] = seq.begin();
                } else {
                    // not found and below the cap
                    seq.push_front(KV(key, value));
                    myCache[key] = seq.begin();
                }
            }
        }
    };
    

    Can someone help me figure out what's the problem?

    Thanks in advanced.


  • 0
    Y

    if(myCache.size() >= cap) {
    seq.pop_back();
    seq.push_front(KV(key, value));
    myCache.erase(key);
    myCache[key] = seq.begin();
    myCache.erase(key);
    the key dose not in the cache


  • 0
    N

    @yxp1949 You are correct. I will fix it.
    Thank you.


Log in to reply
 

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