Day 129LRUキャッシュをOrderedDictで実装する

2026-07-03 JST ・ 難易度: 実用 ・ カテゴリ: 実用データ構造

Pythonコード

1from collections import OrderedDict2 3class LRUCache:4    def __init__(self, capacity):5        self.capacity = capacity6        self.cache = OrderedDict()7 8    def get(self, key):9        if key in self.cache:10            value = self.cache.pop(key)11            self.cache[key] = value12            return value13        else:14            return -115 16    def put(self, key, value):17        if key in self.cache:18            self.cache.pop(key)19        elif len(self.cache) >= self.capacity:20            self.cache.popitem(last=False)21        self.cache[key] = value22 23# LRUキャッシュの使用例24 cache = LRUCache(2)25 cache.put(1, 1)26 cache.put(2, 2)27 print(cache.get(1))  # 128 cache.put(3, 3)29 print(cache.get(2))  # -1

解説

次に試してみよう