C++ solution


  • 0
    J

    '''

    class LRUCache{
    public:
    unordered_map<int, int> cnt;
    unordered_map<int, int> kvs;
    int cap;
    static int k;
    priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, greater<pair<int, pair<int, int>>>> q;

    LRUCache(int capacity) {
        cap = capacity;
    }
    
    int get(int key) {
    
        if (!kvs.count(key)) return -1;
        else 
        {
            while (kvs.size() > cap)
            {
                cnt[q.top().second.first]--;
                if (cnt[q.top().second.first] == 0) 
                {
                    kvs.erase(q.top().second.first);
                }
                q.pop();
            }
            if (kvs.count(key))
            {
                q.push(make_pair(++k, make_pair(key, kvs[key])));
                cnt[key]++;
            }
            
            return kvs.count(key)?kvs[key]:-1;
        }
    }
    
    void set(int key, int value) {
        kvs[key] = value;
        cnt[key]++;
        q.push(make_pair(++k, make_pair(key, value)));
    }
    

    };

    int LRUCache::k = 0;

    '''


Log in to reply
 

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