LRU演算法——python實現__演算法

來源:互聯網
上載者:User

在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 (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 should invalidate the least recently used item before inserting a new item. 設計一個LRU cache,實現兩個功能:(cache中存放著(key,value)索引值對)

get(key):擷取key對應的value,如果key不在cache中那麼返回-1(value 總是為正數);

set(key, value):如果key在cache中則更新它的value;如果不在則插入,如果cache已滿則先刪除最近最少使用的一項後在插入。


對於get,如果key在cache中,那個get(key)表示了對key的一次訪問;而set(key,value)則總是表示對key的一次訪問。

使用一個list來記錄訪問的順序,最先訪問的放在list的前面,最後訪問的放在list的後面,故cache已滿時,則刪除list[0],然後插入新項;

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 key != 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, an 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





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.