C++ 96ms, very very easy-understanding


  • 1
    X
    class LRUCache {
    public:
    	unordered_map<int, int> m1;
    	unordered_map<int, list<int>::iterator> m2;
    	int capacity;
    	list<int> l;
    
    	LRUCache(int capacity): capacity(capacity){
    
    	} 
    	int get(int key) {
    		if (m1.find(key) == m1.end()) {
    			return -1;
    		}
    		l.erase(m2[key]);
    		l.push_front(key);
    		m2[key] = l.begin();
    		return m1[key];
    	}
    	void set(int key, int value) {
    		if (m1.find(key) == m1.end()) {
    			if (m1.size() >= capacity) {
    				int back = l.back();
    				l.pop_back();
    				m1.erase(back);
    			}
    		}
    		else {
    		    l.erase(m2[key]);
    		}
    		l.push_front(key);
    		m1[key] = value;
    		m2[key] = l.begin();
    	}
    };

  • 0
    F

    It is missing the call to erase the key in m2 map

    m1.erase(back);
    m2.erase(back);

  • 0
    X

    oh you are right ! thank you.


Log in to reply
 

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