@@ -30,68 +30,24 @@ cache.get(4); // returns 4
30
30
31
31
## 思路
32
32
33
- 由于是保留是最近使用的N条数据,这就和队列的特性很符合, 先进入队列的,先出队列。
33
+ ` 本题已被收录到我的新书中,敬请期待~ `
34
34
35
- 因此思路就是用一个队列来记录目前缓存的所有key, 每次push都进行判断,如果
36
- 超出最大容量限制则进行清除缓存的操作, 具体清除谁就按照刚才说的队列方式进行处理,同时对key进行入队操作。
35
+ 由于是保留是最近使用的 N 条数据,这就和队列的特性很符合, 先进入队列的,先出队列。
37
36
38
- get的时候,如果缓存中有,则调整队列(具体操作为删除指定元素和入队两个操作)。 缓存中没有则返回-1
37
+ 因此思路就是用一个队列来记录目前缓存的所有 key, 每次 push 都进行判断,如果
38
+ 超出最大容量限制则进行清除缓存的操作, 具体清除谁就按照刚才说的队列方式进行处理,同时对 key 进行入队操作。
39
+
40
+ get 的时候,如果缓存中有,则调整队列(具体操作为删除指定元素和入队两个操作)。 缓存中没有则返回-1
39
41
40
42
## 关键点解析
41
43
42
44
- 队列简化操作
43
45
44
46
- 队列的操作是这道题的灵魂, 很容易少考虑情况
45
47
46
-
47
48
## 代码
48
49
49
50
``` js
50
- /*
51
- * @lc app=leetcode id=146 lang=javascript
52
- *
53
- * [146] LRU Cache
54
- *
55
- * https://leetcode.com/problems/lru-cache/description/
56
- *
57
- * algorithms
58
- * Hard (24.17%)
59
- * Total Accepted: 272.8K
60
- * Total Submissions: 1.1M
61
- * Testcase Example: '["LRUCache","put","put","get","put","get","put","get","get","get"]\n[[2],[1,1],[2,2],[1],[3,3],[2],[4,4],[1],[3],[4]]'
62
- *
63
- *
64
- * Design and implement a data structure for Least Recently Used (LRU) cache.
65
- * It should support the following operations: get and put.
66
- *
67
- *
68
- *
69
- * get(key) - Get the value (will always be positive) of the key if the key
70
- * exists in the cache, otherwise return -1.
71
- * put(key, value) - Set or insert the value if the key is not already present.
72
- * When the cache reached its capacity, it should invalidate the least recently
73
- * used item before inserting a new item.
74
- *
75
- *
76
- * Follow up:
77
- * Could you do both operations in O(1) time complexity?
78
- *
79
- * Example:
80
- *
81
- * LRUCache cache = new LRUCache( 2 );
82
- *
83
- * cache.put(1, 1);
84
- * cache.put(2, 2);
85
- * cache.get(1); // returns 1
86
- * cache.put(3, 3); // evicts key 2
87
- * cache.get(2); // returns -1 (not found)
88
- * cache.put(4, 4); // evicts key 1
89
- * cache.get(1); // returns -1 (not found)
90
- * cache.get(3); // returns 3
91
- * cache.get(4); // returns 4
92
- *
93
- *
94
- */
95
51
/**
96
52
* @param {number} capacity
97
53
*/
@@ -151,5 +107,6 @@ LRUCache.prototype.put = function(key, value) {
151
107
* obj.put(key,value)
152
108
*/
153
109
154
-
155
110
```
111
+
112
+ 本题删除的时间复杂度是不符合要求的。 应该采用双向链表在 O(1) 时间找到前驱进行删除。
0 commit comments