题解 | #设计LRU缓存结构#

设计LRU缓存结构

http://www.nowcoder.com/practice/5dfded165916435d9defb053c63f1e84

class Solution:

def __init__(self, capacity: int):
    # write code here
    self.capacity = capacity
    self.lru_dict = dict()
    self.lru_list = list()

def get(self, key: int) -> int:
    # write code here
    if key not in self.lru_list:
        return -1
    self.lru_list.remove(key)
    self.lru_list.append(key)
    return self.lru_dict[key]

def set(self, key: int, value: int) -> None:
    # write code here
    if len(self.lru_list) < self.capacity and key not in self.lru_list:
        self.lru_list.append(key)
    else:
        pop_key = self.lru_list.pop(0)
        self.lru_dict.pop(pop_key)
        self.lru_list.append(key)
    self.lru_dict[key] = value
    return None

Your Solution object will be instantiated and called as such:

solution = Solution(capacity)

output = solution.get(key)

solution.set(key,value)

全部评论
leetcode 无法通过
点赞 回复 分享
发布于 2022-08-27 20:43 台湾

相关推荐

爱看电影的杨桃allin春招:我感觉你在炫耀
点赞 评论 收藏
分享
评论
2
收藏
分享
牛客网
牛客企业服务