0146._LRU_Cache

0146. LRU Cache

难度: 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:

1
2
3
4
5
6
7
8
9
10
11
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%的用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* @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)
*/