Can anyone please help me with my code (showing tle)


  • 0
    S

    class LRUCache{
    public:

    int capa;
    list<pair<int,int> > l ; // pair(value,key)
    unordered_map<int , list<pair<int,int>>::iterator > keyToIterator; // map from key to iterator
    LRUCache(int capacity) {   	    
    	capa = capacity;
    }
    
    int get(int key) 
    {
    	if( keyToIterator.find(key) == keyToIterator.end() )
    		return -1;
    	else
    	{
    		pair<int,int> val = *keyToIterator[key];
    		l.erase(keyToIterator[key]);
    		l.push_front(val);
    		keyToIterator[key] = l.begin();
    		return val.first;
    	}			
    }
    
    void set(int key, int value) 
    {
       if( l.size() == capa )
       {
    	if( keyToIterator.find(key) == keyToIterator.end())
    	{
    		keyToIterator.erase(l.back().second);
    		l.pop_back();
    		l.push_front(make_pair(value,key));
    		keyToIterator[key] = l.begin();
    	}
    	else
    	{
    		l.erase(keyToIterator[key]);
    		l.push_front(make_pair(value,key));
    		keyToIterator[key] = l.begin();
    	}
       }
       else
       {
    	if( keyToIterator.find(key) == keyToIterator.end() )
    	{
    		l.push_front(make_pair(value,key));
    		keyToIterator[key] = l.begin();
    	}
    	else
    	{
    		l.erase(keyToIterator[key]);
    		l.push_front(make_pair(value,key));
    		keyToIterator[key] = l.begin();
    	}
       }    	
    }    	
    

    };


Log in to reply
 

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