刷题记录:LRU

LRU

# jonas 2022.1.6
class Doublelist:
    def __init__(self, key=None, val=None, pre=None, _next=None):
        # key value pair
        self.key = key
        self.val = val

        # pointer to the pre,next node
        self.pre = pre
        self.next = _next
class LRUCache:

    def __init__(self, capacity: int):
        self.cap = capacity
        self.hashMap = {}
        self.head = Doublelist()
        self.end = Doublelist()
        self.head.next = self.end
        self.end.pre = self.head

    def len(self):
        return len(self.hashMap)

    def get(self, key: int) -> int:
        # return -1 or value of the key
        if key in self.hashMap:
            # adjust the key to the head of the list
            node = self.hashMap[key][1]
            node.pre.next = node.next
            node.next.pre = node.pre

            node.pre = self.head
            node.next = self.head.next
            node.next.pre = node
            node.pre.next = node
            return self.hashMap[key][0]
        else:
            return -1

    def put(self, key: int, value: int) -> None:
        if key in self.hashMap:
            # update
            self.hashMap[key][0] = value
            # adjust the corresponding node to the head of the list
            node = self.hashMap[key][1]

            node.pre.next = node.next
            node.next.pre = node.pre

            node.pre = self.head
            node.next = self.head.next
            self.head.next.pre = node
            self.head.next = node
            return
        if key not in self.hashMap and self.len() < self.cap:
            # creat a new node for the key-value pair
            node = Doublelist(key, value, self.head, self.head.next)
            # add key-val pair and the corresponding node
            self.hashMap[key] = [value, node]
            # link the key-value pair to the head of the list
            self.head.next.pre = node
            self.head.next = node
            return

        if key not in self.hashMap and self.len() == self.cap:
            # remove the last node of the list and corresponding key-value pair
            node = self.end.pre
            del self.hashMap[node.key]

            node.pre.next = node.next
            node.next.pre = node.pre
            # creat a new node for key-value pair
            node = Doublelist(key, value, self.head, self.head.next)
            # add key-val pair and the corresponding node
            self.hashMap[key] = [value, node]
            self.head.next.pre = node
            self.head.next = node
            return
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值