[Leetcode] LRU Cache @ Python

Source: Internet
Author: User

[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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.