在LeetCode上看到這麼一道題:
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. 設計一個LRU cache,實現兩個功能:(cache中存放著(key,value)索引值對)
get(key):擷取key對應的value,如果key不在cache中那麼返回-1(value 總是為正數);
set(key, value):如果key在cache中則更新它的value;如果不在則插入,如果cache已滿則先刪除最近最少使用的一項後在插入。
對於get,如果key在cache中,那個get(key)表示了對key的一次訪問;而set(key,value)則總是表示對key的一次訪問。
使用一個list來記錄訪問的順序,最先訪問的放在list的前面,最後訪問的放在list的後面,故cache已滿時,則刪除list[0],然後插入新項;
class LRUCache: # @param capacity, an integer def __init__(self, capacity): self.cache = {} self.used_list = [] self.capacity = capacity # @return an integer def get(self, key): if key in self.cache: if key != self.used_list[-1]: self.used_list.remove(key) self.used_list.append(key) return self.cache[key] else: return -1 # @param key, an integer # @param value, an integer # @return nothing def set(self, key, value): if key in self.cache: self.used_list.remove(key) elif len(self.cache) == self.capacity: self.cache.pop(self.used_list.pop(0)) self.used_list.append(key) self.cache[key] = value