3.0 KiB
3.0 KiB
题目地址
https://leetcode.com/problems/lru-cache/description/
题目描述
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
思路
本题已被收录到我的新书中,敬请期待~
由于是保留是最近使用的 N 条数据,这就和队列的特性很符合, 先进入队列的,先出队列。
因此思路就是用一个队列来记录目前缓存的所有 key, 每次 push 都进行判断,如果 超出最大容量限制则进行清除缓存的操作, 具体清除谁就按照刚才说的队列方式进行处理,同时对 key 进行入队操作。
get 的时候,如果缓存中有,则调整队列(具体操作为删除指定元素和入队两个操作)。 缓存中没有则返回-1
关键点解析
-
队列简化操作
-
队列的操作是这道题的灵魂, 很容易少考虑情况
代码
/**
* @param {number} capacity
*/
var LRUCache = function(capacity) {
this.cache = {};
this.capacity = capacity;
this.size = 0;
this.queue = [];
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
const hit = this.cache[key];
if (hit !== undefined) {
this.queue = this.queue.filter(q => q !== key);
this.queue.push(key);
return hit;
}
return -1;
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, value) {
const hit = this.cache[key];
// update cache
this.cache[key] = value;
if (!hit) {
// invalid cache and resize size;
if (this.size === this.capacity) {
// invalid cache
const key = this.queue.shift();
this.cache[key] = undefined;
} else {
this.size = this.size + 1;
}
this.queue.push(key);
} else {
this.queue = this.queue.filter(q => q !== key);
this.queue.push(key);
}
};
/**
* 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)
*/
本题删除的时间复杂度是不符合要求的。 应该采用双向链表在 O(1) 时间找到前驱进行删除。