2008 年 9 月 13 日 00:32:00 約 2 分鐘 124 字 274 個單字
題目
原題頁面:https://leetcode.com/problems/lru-cache/
題目型別:Design
難度評價:Hard
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快取。最近最少使用LRU表的定義就不多說了,需要實現的get方法是根據key取value的,因此顯然需要一個map,在Python裡叫關聯陣列的幫助。雖然在leetcode中這道題被標為Hard級別,但其實這只是一道工程性質的題目。
另外貌似這道題目的test cases裡沒有capacity=0的情況?這還是leetcode一貫的作風麼?
程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 class LRUCache : class LRUNode : def __init__ (self, key, value ): self .prev = None self .next = None self .key = key self .value = value def __init__ (self, capacity ): self .map = { } self .list_head = LRUCache.LRUNode(-1 , -1 ) self .list_tail = LRUCache.LRUNode(-1 , -1 ) self .list_head.next = self .list_tail self .list_tail.prev = self .list_head self .capacity = capacity def remove_node (self, node ): node.prev.next = node.next node.next .prev = node.prev def append_node (self, new_node ): last_node = self .list_tail.prev last_node.next = new_node new_node.prev = last_node new_node.next = self .list_tail self .list_tail.prev = new_node def get (self, key ): if self .map .has_key(key): cur = self .map .get(key) self .remove_node(cur) self .append_node(cur) return cur.value else : return -1 def set (self, key, value ): if self .capacity <= 0 : return elif self .map .has_key(key): old_node = self .map .get(key) self .remove_node(old_node) old_node.value = value self .append_node(old_node) else : if len (self .map ) >= self .capacity: del_node = self .list_head.next self .remove_node(del_node) del self .map [del_node.key] new_node = LRUCache.LRUNode(key, value) self .append_node(new_node) self .map [key] = new_node
本文地址:https://xnerv.wang/zh-tw/leetcode-lru-cache/