Why get runtime error in leetcode while run correct in local environment with same easy input


  • 0
    D

    I use linked list to decide which should be delelte when cache size is full.
    and use map to store key and values, my code is as follow:
    When use a key or get a new key, i insert change it to the head of linked list,and delete in linked head end
    In this test case, leetcode return runtime error, but I get correct answer in local visual studio
    Last executed input: 2,[set(2,1),set(2,2),get(2),set(1,1),set(4,1),get(2)]

      typedef struct Node
          {
        	Node()
        	{
        		key = 0;
        		pre = NULL;
        		next = NULL;
        	}
        	int key;
        	Node* pre;
        	Node* next;
        }Node;
    
    class LRUCache
    {
    public:
    	LRUCache(int capacity)
    	{
    		sz = 0;
    		cap = capacity;
    		head.next = NULL;
    		end.next = NULL;
    	}
    ~LRUCache()
    {
    	Node* tmp = head.next;
    	Node* d;
    	while (tmp)
    	{
    		d = tmp;
    		tmp = tmp->next;
    		delete d;
    	}
    }
    void changePos(int key)
    {
    	Node* tmp = head.next;
    
    	while (tmp)
    	{
    		if (tmp->key == key)
    			break;
    		tmp = tmp->next;
    	}
    
    	if (tmp->pre && tmp->next)
    	{
    		Node *p = tmp->pre;
    		p->next = tmp->next;
    		tmp->next->pre = p;
    	}
    	else if (tmp->pre)
    	{
    		end.next = tmp->pre;
    	}
    	else{
    
    		;
    	}
    	head.next = tmp;
    }
    
    void insertHead(int key)
    {
    	Node* tmp = head.next;
    	Node* newnode = new Node;
    	newnode->key = key;
    	head.next = newnode;
    	if (end.next == NULL)
    		end.next = newnode;
    	if (tmp){
    		newnode->next = tmp;
    		tmp->pre = newnode;
    	}
    }
    
    int get(int key)
    {
    	if (cache.find(key) == cache.end())
    		return -1;
    	changePos(key);
    	return cache[key];
    }
    void set(int key, int value)
    {
    	if (cache.find(key) == cache.end())
    	{
    		if (sz < cap)
    		{
    			sz++;
    		}
    		else{
    
    			Node *tmp = end.next;
    			end.next = tmp->pre;
    			cache.erase(tmp->key);
    			if (tmp->pre)
    				tmp->pre->next = NULL;
    			delete tmp;
    		}
    		insertHead(key);
    	}
    	else
    	{
    		changePos(key);
    
    	}
    	cache[key] = value;
    }
    int cap;
    int sz;
    Node head, end;
    map<int, int> cache;
    

    };


  • 0
    R

    can you please say how did you solve it? I have thesame issue


Log in to reply
 

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