[Leetcode] LRU Cache @ Python

Source: Internet
Author: User

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

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.