運用你所掌握的數據結構,設計和實現一個 LRU (最近最少使用) 緩存機制。它應該支持如下操做: 獲取數據 get 和 寫入數據 put 。緩存
獲取數據 get(key) - 若是密鑰 (key) 存在於緩存中,則獲取密鑰的值(老是正數),不然返回 -1。
寫入數據 put(key, value) - 若是密鑰不存在,則寫入其數據值。當緩存容量達到上限時,它應該在寫入新數據以前刪除最近最少使用的數據值,從而爲新的數據值留出空間。數據結構
進階:spa
你是否能夠在 O(1) 時間複雜度內完成這兩種操做?設計
示例:code
LRUCache cache = new LRUCache( 2 /* 緩存容量 */ );blog
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 該操做會使得密鑰 2 做廢
cache.get(2); // 返回 -1 (未找到)
cache.put(4, 4); // 該操做會使得密鑰 1 做廢
cache.get(1); // 返回 -1 (未找到)
cache.get(3); // 返回 3
cache.get(4); // 返回 4ci
能夠用標準的哈希表在 O(1)O(1) 時間內完成。leetcode
有一種叫作有序字典的數據結構,綜合了哈希表和鏈表,在 Python 中爲 OrderedDict,在 Java 中爲 LinkedHashMap。get
leetcode題解it
1 from collections import OrderedDict 2 class LRUCache(OrderedDict): 3 4 def __init__(self, capacity): 5 """ 6 :type capacity: int 7 """ 8 self.capacity = capacity 9 10 def get(self, key): 11 """ 12 :type key: int 13 :rtype: int 14 """ 15 if key not in self: 16 return -1 17 18 self.move_to_end(key) 19 return self[key] 20 def put(self, key, value): 21 """ 22 :type key: int 23 :type value: int 24 :rtype: None 25 """ 26 if key in self: 27 self.move_to_end(key) 28 self[key]=value 29 if len(self)>self.capacity: 30 self.popitem(last=False)