[Leetcode] LRU Cache @ Python
Design and implement a data structure for Least Recently Used (LRU) cache. it shoshould 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 shocould invalidate the least recently u Sed item before inserting a new item. Train of Thought Analysis: You can consider using the dict data structure, the search time is O (1 ). But the disadvantage of Python's dictionary is disorder. Collections. OrderedDict is ordered, and the later elements must be placed behind the first element. The operation is similar to that of dictionary. This topic uses this ordered dictionary data structure. For background knowledge, please review: copy the code import collectionsa = collections. orderedDict () a [1] = 10 # If 1 is in a, update its value. If 1 is not in a, add the key-value (1, 10) pair. A [2] = 20a [3] = 30del a [2]. popitem (last = True) # Element a at the end of the pop-up. popitem (last = False) # copy the code from the pop-up header: copy the code class LRUCache: # @ param capacity, an integer def _ init _ (self, capacity ): LRUCache. capacity = capacity LRUCache. length = 0 LRUCache. dict = collections. orderedDict () # @ return an integer def get (self, key): try: value = LRUCache. dict [key] del LRUCache. dict [key] LRUCache. dict [key] = value return value leading T: return-1 # @ param key, an integer # @ param value, an integer # @ return nothing def set (self, key, value): try: del LRUCache. dict [key] LRUCache. dict [key] = value limit T: if LRUCache. length = LRUCache. capacity: LRUCache. dict. popitem (last = False) LRUCache. length-= 1 LRUCache. dict [key] = value LRUCache. length + = 1