难度: Medium
原题链接
内容描述
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.
The cache is initialized with a positive capacity.
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
思路1
- 时间复杂度: O(1)- 空间复杂度: O(N)******
这是一道数据结构的考题。
简单的获取和插入,顺序不做考虑,所以数据结构用Object即可。
但是重要的考点——LRU,也就是删除最近没有使用的数据。所以想到用队列
存在key列表:
- 未超过存储上限时,每次
put
一个新数据时,向队列末尾插入当前key
- 每次
get
时,如果key存在,则将对应的key从的队列中,移到对末尾 - 在超过存储上限时,如进行
put
操作,则将队列首位删除掉
执行用时 :492 ms, 在所有 JavaScript 提交中击败了35.29%的用户
内存消耗 :59.7 MB, 在所有 JavaScript 提交中击败了16.36%的用户
/**
* @param {number} capacity
*/
var LRUCache = function(capacity) {
this.limit = capacity || 2
this.storage = {}
this.keyList = []
};
/**
* @param {number} key
* @return {number}
*/
LRUCache.prototype.get = function(key) {
if (this.storage.hasOwnProperty(key)) {
let index = this.keyList.findIndex(k => k === key)
this.keyList.splice(index, 1)
this.keyList.push(key)
return this.storage[key]
} else {
return -1
}
};
/**
* @param {number} key
* @param {number} value
* @return {void}
*/
LRUCache.prototype.put = function(key, value) {
// 判断容量
if (this.keyList.length >= this.limit && !this.storage.hasOwnProperty(key)) {
this.deleteLRU()
}
// 存储数据
this.updateKeyList(key)
this.storage[key] = value
};
LRUCache.prototype.deleteLRU = function () {
delete this.storage[this.keyList.shift()]
}
LRUCache.prototype.updateKeyList = function (key) {
if (this.storage.hasOwnProperty(key)) {
var index = this.keyList.findIndex(k => key === k)
this.keyList.splice(index, 1)
}
this.keyList.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)
*/