150强访谈简单

LRU缓存

“LRU 缓存”问题的详细指南和 Python 实现。

问题陈述

简单

设计一个遵循最近最少使用 (LRU) 缓存约束的数据结构。

实现LRUCache类:

- LRUCache(capacity: int) - 使用正大小的容量初始化 LRU 缓存。

- get(key: int) -> int - 如果键存在则返回键的值,否则返回-1。

- put(key: int, value: int) -> None - 如果键存在则更新键的值。否则,将键值对添加到缓存中。如果密钥数量超过容量,则逐出最近最少使用的密钥。

get 和 put 函数必须以 O(1) 平均时间复杂度运行。

输入是操作列表和参数列表。实现一个返回结果列表的函数 lruCache(operations: list, arguments: list) -> list (对于构造函数和 put 为 None)。

约束条件
  • 1 <= capacity <= 3000
  • 0 <= key <= 10000
  • 0 <= value <= 100000
  • At most 200000 calls will be made to get and put

示例

Example 1
Input
["LRUCache","put","put","get","put","get","put","get","get","get"], [[2],[1,1],[2,2],[1],[3,3],[2],[4,4],[1],[3],[4]]
Output
[None,None,None,1,None,-1,None,-1,3,4]
Explanation

Cache capacity is 2. put(1,1), put(2,2), get(1) returns 1. put(3,3) evicts key 2. get(2) returns -1 (evicted). put(4,4) evicts key 1. get(1) returns -1, get(3) returns 3, get(4) returns 4.

Need a Hint?
考虑使用特定于链接列表的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。