(力扣记录)146. LRU 缓存

数据类型:链表

**时间复杂度:**O(1)

**空间复杂度:**O(N)

代码实现:

python 复制代码
class Node:

    def __init__(self, key=-1, value=-1):
        self.key = key
        self.val = value
        self.next = None
        self.prev = None

class LRUCache:

    def __init__(self, capacity: int):
        self.map = dict()
        self.cap = capacity
        self.left = Node()
        self.right = Node()
        self.right.prev = self.left
        self.left.next = self.right

    def pop(self, node: Node):
        node.prev.next, node.next.prev = node.next, node.prev

    def push(self, node: Node):
        last = self.right.prev
        last.next = node
        node.prev, node.next = last, self.right
        self.right.prev = node

    def get(self, key: int) -> int:
        if key not in self.map: return -1
        self.pop(self.map[key])
        self.push(self.map[key])
        return self.map[key].val

    def put(self, key: int, value: int) -> None:
        if key in self.map:
            self.pop(self.map[key])
        elif self.cap == len(self.map):
            self.map.pop(self.left.next.key)
            self.pop(self.left.next)
        self.push(Node(key, value))
        self.map[key] = self.right.prev
        


# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
相关推荐
ghie909020 分钟前
基于MATLAB的遗传算法优化支持向量机实现
算法·支持向量机·matlab
久未28 分钟前
Pytorch autoload机制自动加载树外扩展(Autoload Device Extension)
人工智能·pytorch·python
java1234_小锋43 分钟前
TensorFlow2 Python深度学习 - TensorFlow2框架入门 - 使用Keras.Model来定义模型
python·深度学习·tensorflow·tensorflow2
Learn Beyond Limits1 小时前
TensorFlow Implementation of Content-Based Filtering|基于内容过滤的TensorFlow实现
人工智能·python·深度学习·机器学习·ai·tensorflow·吴恩达
java1234_小锋1 小时前
TensorFlow2 Python深度学习 - 函数式API(Functional API)
python·深度学习·tensorflow·tensorflow2
Y200309161 小时前
使用 PyTorch 实现 MNIST 手写数字识别
python
马尚来1 小时前
移动端自动化测试Appium,从入门到项目实战Python版
python
朝新_1 小时前
【优选算法】第一弹——双指针(上)
算法
天才测试猿1 小时前
WebUI自动化测试:POM设计模式全解析
自动化测试·软件测试·python·selenium·测试工具·设计模式·测试用例
艾莉丝努力练剑1 小时前
【C++STL :stack && queue (一) 】STL:stack与queue全解析|深入使用(附高频算法题详解)
linux·开发语言·数据结构·c++·算法