未验证 提交 07df1c39 编写于 作者: 片刻小哥哥's avatar 片刻小哥哥 提交者: GitHub

谢谢小哥哥 | Merge pull request #271 from royIdoodle/master

0146. LRU Cache
# 0146. LRU Cache
**<font color=red>难度: Medium</font>**
## 刷题内容
> 原题链接
* https://leetcode.com/problems/lru-cache/
> 内容描述
Design and implement a data structure for [Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU). 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](https://baike.baidu.com/item/LRU/1269842?fr=aladdin),也就是删除最近没有使用的数据。所以想到用`队列`存在key列表:
* 未超过存储上限时,每次`put`一个新数据时,向队列末尾插入当前`key`
* 每次`get`时,如果key存在,则将对应的key从的队列中,移到对末尾
* 在超过存储上限时,如进行`put`操作,则将队列首位删除掉
> 执行用时 :492 ms, 在所有 JavaScript 提交中击败了35.29%的用户
>
> 内存消耗 :59.7 MB, 在所有 JavaScript 提交中击败了16.36%的用户
```javascript
/**
* @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)
*/
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册