Simple JavaScript solution using just one Map


  • 0
    E
    var LRUCache = function(capacity) {
        this.cache = new Map();             // { k1: v1, k2: v2, ... }
        this.capacity = capacity;
    };
    
    LRUCache.prototype.get = function(key) {
        let v = this.cache.get(key);
        if (v !== undefined) {
            let t = new Date().getTime();
            this.cache.delete(key);
            this.cache.set(key, v);
            return v;
        }
        return -1;
    };
    
    LRUCache.prototype.set = function(key, value) {
        let t = new Date().getTime();
        if (this.cache.get(key) !== undefined) {
            this.cache.delete(key);
            this.cache.set(key, value);
        }
        else {
            if (this.cache.size == this.capacity) {
                for (var k of this.cache.keys()) {
                    this.cache.delete(k);
                    break;
                }
            }
            this.cache.set(key, value);
        }
    };
    

Log in to reply
 

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