leetcode146 LRU Cache
1 """ 2 Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. 3 get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. 4 put(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. 5 The cache is initialized with a positive capacity. 6 Follow up: 7 Could you do both operations in O(1) time complexity? 8 Example: 9 LRUCache cache = new LRUCache( 2 /* capacity */ ); 10 cache.put(1, 1); 11 cache.put(2, 2); 12 cache.get(1); // returns 1 13 cache.put(3, 3); // evicts key 2 14 cache.get(2); // returns -1 (not found) 15 cache.put(4, 4); // evicts key 1 16 cache.get(1); // returns -1 (not found) 17 cache.get(3); // returns 3 18 cache.get(4); // returns 4 19 """ 20 """ 21 用dict存储元素 22 用list存储dict里的key 23 用list里的insert函数和index函数pop函数来维护队列 24 保证能在队头加元素,删除任意index位置元素 25 """ 26 class LRUCache: 27 28 def __init__(self, capacity: int): 29 self.len = capacity 30 self.d = {} 31 self.l = [] 32 33 def get(self, key: int) -> int: 34 val = self.d.get(key) 35 if val and self.l[0] != key: #如果查找的值不在队头 36 index = self.l.index(key) 37 self.l.pop(index) 38 self.l.insert(0, key) 39 val = val if val else -1 40 return val 41 42 def put(self, key: int, value: int) -> None: 43 if self.d.get(key): #如果重复 44 index = self.l.index(key) 45 self.d.pop(key) 46 self.l.pop(index) 47 if len(self.l) >= self.len: #如果队满 48 x = self.l.pop(-1) 49 self.d.pop(x) 50 self.d[key] = value 51 self.l.insert(0, key)