Why runtime error? My code runs fine in Xcode but not in OJ, T T


  • 1
    M
    class LRUCache{
    private:
        struct ListNode {
            ListNode *next;
            int key;
            int value;
            ListNode(int k, int v):key(k), value(v), next(NULL){}
        };
        int cap;
        int cur_size;
        ListNode *head;
        ListNode *tail;
        unordered_map<int, ListNode*> helper;
    public:
        LRUCache(int capacity) {
            cap = capacity;
            ListNode *dummy = new ListNode(0,0);
            head = dummy;
            tail = dummy;
            cur_size = 0;
        }
        int get(int key) {
            if(helper.find(key)!=helper.end()) {
                ListNode *aim = helper[key];
                tail->next = new ListNode(key, aim->value);
                tail = tail->next;
                ListNode *temp = aim->next;
                if(temp!=NULL) {
                    aim->next = temp->next;
                    aim->key = temp->key;
                    aim->value = temp->value;
                    delete temp;
                } else {
                    aim = NULL;
                }
                helper[key] = tail;
                return tail->value;
            }
            return -1;
        }
        
        void set(int key, int value) {
            tail->next = new ListNode(key, value);
            tail = tail->next;
            if(helper.find(key)!=helper.end()) {
                ListNode *aim = helper[key];
                ListNode *temp = aim->next;
                if(temp!=NULL) {
                    aim->next = temp->next;
                    aim->key = temp->key;
                    aim->value = temp->value;
                    delete temp;
                } else {
                    aim = NULL;
                }
            } else {
                if(cur_size < cap) {
                    cur_size++;
                } else {
                    ListNode *dump = head;
                    head = head->next;
                    helper.erase(dump->next->key);
                    delete dump;
                }
            }
            helper[key] = tail;
        }
    };

Log in to reply
 

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