zoukankan      html  css  js  c++  java
  • 【leetcode】LRU Cache

    题目简述:

    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.

    解题思路:

    用一个队列存放当前的元素,用字典结构表示cache

    #coding=utf-8
    class LRUCache:
    
        # @param capacity, an integer
        def __init__(self, capacity):
            self.cap = capacity
            self.cache = {}
            self.sta = []
            
        # @return an integer
        def get(self, key):
            if key in self.cache:
                self.sta.remove(key)
                self.sta.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 self.cap == len(self.cache) and (key not in self.cache):
                self.cache.pop(self.sta[0])
                self.sta.pop(0)
            if key in self.cache:
                self.sta.remove(key)
                self.sta.append(key)
            else:
                self.sta.append(key)
            self.cache[key] = value
  • 相关阅读:
    手机端不加载js文件,PC端要加载js文件
    JS数组去重和取重
    jquery遍历一个数组
    2个轮播地址
    动感Loading文字
    仿265网站LOGO,会盯着你看的眼睛
    git学习
    c++ primer 5th 笔记:第十一章
    c++ primer 5th 笔记:第十章
    c++ primer 5th 笔记:第九章
  • 原文地址:https://www.cnblogs.com/MrLJC/p/4283588.html
Copyright © 2011-2022 走看看