【路飞】算法与数据结构-面试题 16.25. LRU 缓存

125 阅读2分钟

不管全世界所有人怎么说,我都认为自己的感受才是正确的。无论别人怎么看,我绝不打乱自己的节奏。喜欢的事自然可以坚持,不喜欢的怎么也长久不了。

LeetCode:原题地址

题目要求

设计和构建一个“最近最少使用”缓存,该缓存会删除最近最少使用的项目。缓存应该从键映射到值(允许你插入和检索特定键对应的值),并在初始化时指定最大容量。当缓存被填满时,它应该删除最近最少使用的项目。

它应该支持以下操作: 获取数据 get 和 写入数据 put 。

获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。 写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。

示例 1:

LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // 返回  1
cache.put(3, 3);    // 该操作会使得密钥 2 作废
cache.get(2);       // 返回 -1 (未找到)
cache.put(4, 4);    // 该操作会使得密钥 1 作废
cache.get(1);       // 返回 -1 (未找到)
cache.get(3);       // 返回  3
cache.get(4);       // 返回  4

思路

  • 一个节点包含key、value、pre和next;
  • 定义两个哨兵节点-头结点、尾节点;
  • 使用map保存所以的节点;
/**
 * @param {number} capacity
 */
var LRUCache = function(capacity) {
 this.capacity = capacity;
    this.head = {};
    this.tail = {};
    this.head.next = this.tail;
    this.tail.pre = this.head;
    this.size = 0;
    this.map = new Map();
};

/** 
 * @param {number} key
 * @return {number}
 */
LRUCache.prototype.get = function(key) {
if (this.map.has(key)) {
        let node = this.map.get(key);
        this.moveToHead(key, node.value);
        return node.value;
    }
    return -1;
};

/** 
 * @param {number} key 
 * @param {number} value
 * @return {void}
 */
LRUCache.prototype.put = function(key, value) {
 if (this.map.has(key)) {
        this.moveToHead(key, value);
    } else {
        if (this.size < this.capacity) {
            this.addHead(key, value)
        } else {
            this.deleteTail();
            this.addHead(key, value);
        }
    }
};
LRUCache.prototype.deleteNode = function (key) {
    let node = this.map.get(key);
    let preNode = node.pre;
    let nextNode = node.next;
    preNode.next = nextNode;
    nextNode.pre = preNode;
    this.size--;
    this.map.delete(key);
}

LRUCache.prototype.deleteTail = function () {
    let tailPre = this.tail.pre;
    tailPre.pre.next = this.tail;
    this.tail.pre = tailPre.pre;
    this.size--;
    this.map.delete(tailPre.key);
}

LRUCache.prototype.addHead = function (key, value) {
    let newNode = { key: key, value: value };
    newNode.next = this.head.next;
    this.head.next.pre = newNode;
    this.head.next = newNode;
    newNode.pre = this.head;
    this.map.set(key, newNode);
    this.size++;
}

LRUCache.prototype.moveToHead = function (key, value) {
    this.deleteNode(key);
    this.addHead(key, value)
}
/**
 * Your LRUCache object will be instantiated and called as such:
 * var obj = new LRUCache(capacity)
 * var param_1 = obj.get(key)
 * obj.put(key,value)
 */