LRU algorithm--python realize __ algorithm

Source: Internet
Author: User

See this problem on the Leetcode:

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 (would 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 item used before a new item. Design a LRU cache, realize two functions: (Cache in the store (key,value) key value pairs)

Get (Key): Gets the value of the key and returns 1 if the key is not in the cache (value is always positive);

Set (key, value): If the key in the cache update its value, if it is not inserted, if the cache is full, first delete the least recently used after the insertion.


For GET, if key is in cache, that get (key) represents an access to key, and set (Key,value) always represents an access to key.

Use a list to record the order of access, the first access is placed in front of the list, the last access is placed behind the list, so the cache is full, then delete list[0], and then insert the new item;

Class LRUCache:

    # @param capacity, an integer
    def __init__ (self, capacity):
        Self.cache = {}
        self.used_ List = []
        self.capacity = capacity

    # @return An integer
    def get (self, key):
        if key in Self.cache:
            if K EY!= self.used_list[-1]:
                self.used_list.remove (key)
                Self.used_list.append (key) return
            self.cache[ Key]
        else:
            return-1

    # @param key, an integer
    # @param value, a integer
    # @return
    Nothing def set (self, key, value):
        if key in Self.cache:
            self.used_list.remove (key)
        elif len (self.cache) = = Self.capacity:
            self.cache.pop (self.used_list.pop (0))
        self.used_list.append (key)
        Self.cache[key] = value





Related Article

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.