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 ('ll 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 is reached its capacity, it should invalidate the least recently used item before inserting a new item.
Thinking analysis: Can consider using DICT data structure, find time is O (1). But Python's dictionary disadvantage is disorder. and collections. Ordereddict are ordered, followed by elements that must be added to the elements before they are joined, and the operations are similar to dictionary. So this topic will be implemented using this ordered dictionary data structure.
As a background knowledge, please review:
Import= collections. Ordereddict () a[# if 1 updates its value in a, if 1 is not in a then add (1, 10) to this pair of key-value. a[2] =a[3] =del a[2# popup element of the tail # popup element of the head
The code is as follows:
classLRUCache:#@param capacity, an integer def __init__(self, capacity): Lrucache.capacity=capacity Lrucache.length=0 lrucache.dict=collections. Ordereddict ()#@return An integer defget (self, key):Try: Value=Lrucache.dict[key]delLrucache.dict[key] Lrucache.dict[key]=valuereturnvalueexcept: return-1#@param key, an integer #@param value, an integer #@return Nothing defset (self, key, value):Try: delLrucache.dict[key] Lrucache.dict[key]=valueexcept: ifLrucache.length = =LRUCache.capacity:LRUCache.dict.popitem ( last=False) Lrucache.length-= 1Lrucache.dict[key]=value Lrucache.length+=1
Reference acknowledgements:
[1]http://chaoren.is-programmer.com/posts/43116.html
[2]http://www.cnblogs.com/zuoyuan/p/3701572.html (This code has 75 lines, the interview is poor; but it's a good practice for two-way lists.)
[Leetcode] LRU Cache @ Python