1 Star 41 Fork 18

小墨/力扣题库(完整版)

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
LRU 缓存 [OrIXps].html 2.36 KB
Copy Edit Raw Blame History
小墨 authored 2023-12-09 18:42 +08:00 . 存量题库数据更新
<div class="title__3Vvk">
<p>运用所掌握的数据结构,设计和实现一个&nbsp; <a href="https://baike.baidu.com/item/LRU" target="_blank">LRU (Least Recently Used,最近最少使用) 缓存机制</a></p>
<p>实现 <code>LRUCache</code> 类:</p>
<ul>
<li><code>LRUCache(int capacity)</code> 以正整数作为容量&nbsp;<code>capacity</code> 初始化 LRU 缓存</li>
<li><code>int get(int key)</code> 如果关键字 <code>key</code> 存在于缓存中,则返回关键字的值,否则返回 <code>-1</code></li>
<li><code>void put(int key, int value)</code>&nbsp;如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。</li>
</ul>
<p>&nbsp;</p>
<p><strong>示例:</strong></p>
<pre>
<strong>输入</strong>
[&quot;LRUCache&quot;, &quot;put&quot;, &quot;put&quot;, &quot;get&quot;, &quot;put&quot;, &quot;get&quot;, &quot;put&quot;, &quot;get&quot;, &quot;get&quot;, &quot;get&quot;]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
<strong>输出</strong>
[null, null, null, 1, null, -1, null, -1, 3, 4]
<strong>解释</strong>
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // 缓存是 {1=1}
lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
lRUCache.get(1); // 返回 1
lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
lRUCache.get(2); // 返回 -1 (未找到)
lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
lRUCache.get(1); // 返回 -1 (未找到)
lRUCache.get(3); // 返回 3
lRUCache.get(4); // 返回 4
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 &lt;= capacity &lt;= 3000</code></li>
<li><code>0 &lt;= key &lt;= 10000</code></li>
<li><code>0 &lt;= value &lt;= 10<sup>5</sup></code></li>
<li>最多调用 <code>2 * 10<sup>5</sup></code><code>get</code><code>put</code></li>
</ul>
</div>
<p>&nbsp;</p>
<p><strong>进阶</strong>:是否可以在&nbsp;<code>O(1)</code> 时间复杂度内完成这两种操作?</p>
<p>&nbsp;</p>
<p><meta charset="UTF-8" />注意:本题与主站 146&nbsp;题相同:<a href="https://leetcode-cn.com/problems/lru-cache/">https://leetcode-cn.com/problems/lru-cache/</a>&nbsp;</p>
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/coder-xiaomo/leetcode-problemset.git
git@gitee.com:coder-xiaomo/leetcode-problemset.git
coder-xiaomo
leetcode-problemset
力扣题库(完整版)
master

Search