Sharing my accepted c++ code with 344ms


  • 0
    L
    class LRUCache{
    public:
        list<int> key_list;
        int max_size;
        int cur_size;
        int temp;
        unordered_map<int,int> page_map;
        unordered_map<int,list<int>::iterator> map_it;
    
        LRUCache(int capacity) {
            max_size = capacity;
            cur_size = 0;
        }
    
        int get(int key) {
            if(page_map.count(key)){
                key_list.erase(map_it[key]);
                key_list.push_front(key);
                map_it[key] = key_list.begin();
                return page_map[key];
            } 
            return -1;
        }
    
        void set(int key, int value) {
            if(page_map.count(key)){
                page_map[key] = value;
                key_list.erase(map_it[key]);
                key_list.push_front(key);
                map_it[key] = key_list.begin();
                return;
            }
            else{
                if(cur_size < max_size){
                    page_map.insert(make_pair(key,value));
                    key_list.push_front(key);
                    map_it.insert(make_pair(key,key_list.begin()));
                    cur_size++;
                }
                else{
                    auto it = key_list.end();
                    it--;
                    page_map.erase(*it);
                    map_it.erase(*it);
                    page_map.insert(make_pair(key,value));
                    key_list.erase(it);
                    key_list.push_front(key);
                    map_it.insert(make_pair(key,key_list.begin()));
                }
            }
        }
    };

Log in to reply
 

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