Apple 设计 LRU Cache,get 与 put 均摊 O(1)

实现一个 LRU 缓存,get 和 put 都要 O(1),在 CoderPad 上用 Python 写并自测。

2024-11OAVO Helper · 面经整理

01 · QUESTIONS

面试题目

  • 实现一个 LRU 缓存,get 和 put 都要 O(1),在 CoderPad 上用 Python 写并自测

02 · ANSWERS

参考答案

用 OrderedDict 维护「键 → 值」并保持使用顺序:访问时移到末尾,超出容量时弹出开头;面试官要求手写时,换成哈希表 + 双向链表。

解题思路

  • OrderedDict 内部就是哈希表 + 双向链表,move_to_end 与 popitem(last=False) 都是 O(1)。
  • 先确认面试官是否允许使用 OrderedDict;不允许时手写节点、哨兵与两个辅助函数(摘下、插到头部)。
  • 自测覆盖:普通读写、更新已有键、淘汰顺序、读操作改变淘汰顺序、容量为 1 或 0。

代码(OrderedDict 版)

from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity):
        self.cap, self.data = capacity, OrderedDict()

    def get(self, key):
        if key not in self.data:
            return -1
        self.data.move_to_end(key)           # 标记为最近使用
        return self.data[key]

    def put(self, key, value):
        if self.cap <= 0:
            return
        self.data[key] = value
        self.data.move_to_end(key)
        if len(self.data) > self.cap:
            self.data.popitem(last=False)    # 淘汰最久未使用

自测

def self_test():
    c = LRUCache(2)
    c.put(1, 1); c.put(2, 2)
    assert c.get(1) == 1          # 1 变为最近使用
    c.put(3, 3)                   # 淘汰 2
    assert c.get(2) == -1
    c.put(1, 10)                  # 更新已有键
    assert c.get(1) == 10 and c.get(3) == 3
    return True

复杂度

  • 时间:get / put 均为 O(1)。
  • 空间:O(capacity)。

联系 OAVO Helper

想针对这题做模拟练习?

加微信咨询陪跑,我们可以按你的目标岗位安排简历、模拟面试或代投。

加微信咨询陪跑微信:aasummer