Leetcode—146. LRU 缓存【中等】(哈希表+双向链表)

2025每日刷题(242)

Leetcode---146. LRU 缓存

实现代码

go 复制代码
type node struct {
    key, val int
    prev, next *node
}

type LRUCache struct {
    capacity int
    cache map[int]*node
    head, tail *node
}

func Constructor(capacity int) LRUCache {
    head := new(node)
    tail := new(node)
    head.next = tail
    tail.prev = head
    return LRUCache{
        capacity: capacity,
        cache: make(map[int]*node, capacity),
        head: head,
        tail: tail,
    }
}


func (this *LRUCache) Get(key int) int {
    n, ok := this.cache[key]
    if !ok {
        return -1
    }
    this.moveToFront(n)
    return n.val
}


func (this *LRUCache) moveToFront(n *node) {
    this.remove(n)
    this.pushToFront(n)
}

func (this *LRUCache) remove(n *node) {
    n.prev.next = n.next
    n.next.prev = n.prev
    n.prev = nil
    n.next = nil
}

func (this *LRUCache) pushToFront(n *node) {
    n.next = this.head.next
    n.prev = this.head
    this.head.next.prev = n
    this.head.next = n
}


func (this *LRUCache) Put(key int, value int)  {
    n, ok := this.cache[key]
    if ok {
        n.val = value
        this.moveToFront(n)
        return
    }

    if len(this.cache) == this.capacity {
        back := this.tail.prev
        this.remove(back)
        delete(this.cache, back.key)
    }
    newnode := &node {
        key: key,
        val: value,
    }
    this.pushToFront(newnode)
    this.cache[key] = newnode
}


/**
 * Your LRUCache object will be instantiated and called as such:
 * obj := Constructor(capacity);
 * param_1 := obj.Get(key);
 * obj.Put(key,value);
 */

运行结果


之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

相关推荐
coder!mq23 分钟前
说几个常见的语法糖?
java·开发语言·算法
不爱学英文的码字机器1 小时前
推荐算法梳理,六种主流模型与九步训练流程
算法·机器学习·推荐算法
thesky1234561 小时前
智能体面试准备(二十六):Agent 成本工程——模型路由、缓存、预算控制与大小模型分工
缓存·llmops·智能体·模型路由·成本工程·预算控制·小模型分工
65岁退休Coder2 小时前
LangChain v1.3.4 笔记 - 07 补充:链式调用 LCEL
后端·python·langchain
白狐_7982 小时前
408数据结构第5章:树与二叉树②——遍历、线索树、森林与哈夫曼
数据结构·算法·深度优先
卷无止境2 小时前
FastAPI 部署在 Nginx 后面到底该怎么配
后端·python
码流怪侠2 小时前
用 WiFi 信号数人头:howmanypeoplearearound 项目深度解析
后端·开源·github
心运软件3 小时前
SpringBoot+ Vue校园社团管理平台的完整架构设计
vue.js·后端
Jodie同志3 小时前
第16~23天:持久化、HITL、流式、MCP与安全
前端·后端·agent