LFU缓存-模拟460-python

python

import sys

class Node:
    def __init__(self, key, val, count=1, prev=None, next=None):
        self.key = key
        self.val = val
        self.count = count
        self.prev = prev
        self.next = next

class DoubleList:
    def __init__(self):
        self.head = Node(0, 0, -sys.maxsize)
        self.tail = Node(0, 0, sys.maxsize)
        self.head.next = self.tail
        self.tail.prev = self.head
        self.size = 0

    def add(self, node):
        count = node.count
        curr = self.tail
        while curr.count > count:
            curr = curr.prev
        tail = curr.next
        curr.next = node
        node.prev = curr
        tail.prev = node
        node.next = tail
        self.size += 1
    
    def remove(self, node):
        node.prev.next = node.next
        node.next.prev = node.prev
        node.next = None
        node.prev = None
        node.count += 1
        self.size -= 1
        return node
    
    def removeFirst(self):
        if self.head.next == self.tail:
            return None
        first = self.head.next
        first = self.remove(first)
        return first.key

class LFUCache:
    def __init__(self, capacity: int):
        self.cap = capacity
        self.map = dict()
        self.doublelist = DoubleList()

    def get(self, key: int):
        if key not in self.map.keys():
            return -1
        node = self.doublelist.remove(self.map[key])
        self.doublelist.add(node)
        return node.val

    def put(self, key: int, value: int):
        if key in self.map.keys():
            node = self.doublelist.remove(self.map[key])
            node.val = value
            self.doublelist.add(node)
        elif self.cap == self.doublelist.size:
            first = self.doublelist.removeFirst()
            if first == None:
                return
            del self.map[first]
            node = Node(key, value, 1)
            self.doublelist.add(node)
            self.map[key] = node
        else:
            node = Node(key, value, 1)
            self.doublelist.add(node)
            self.map[key] = node


# Your LFUCache object will be instantiated and called as such:
# obj = LFUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值