前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LRU算法——python实现

LRU算法——python实现

作者头像
py3study
发布2020-01-06 11:17:56
6450
发布2020-01-06 11:17:56
举报
文章被收录于专栏:python3python3

在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],然后插入新项;

代码语言:javascript
复制
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
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档