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);
 */

运行结果


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

相关推荐
珂朵莉MM7 分钟前
第七届全球校园人工智能算法精英大赛-算法巅峰赛产业命题赛第3赛季优化题--多策略混合算法
人工智能·算法
希望永不加班10 分钟前
SpringBoot 集成测试:@SpringBootTest 与 MockMvc
java·spring boot·后端·log4j·集成测试
罗西的思考14 分钟前
【OpenClaw】通过 Nanobot 源码学习架构---(6)Skills
人工智能·深度学习·算法
uzong14 分钟前
软件人员可以关注的 Skill,亲测确实不错,值得试一下
人工智能·后端
掘金虾17 分钟前
Hono 框架入门到实战:用 Node.js 写一个支持工具调用的流式对话 Agent
后端
枫叶林FYL18 分钟前
【自然语言处理 NLP】7.2 红队测试与对抗鲁棒性(Red Teaming & Adversarial Robustness)
人工智能·算法·机器学习
用户83562907805119 分钟前
Python 自动拆分 Word 文档教程:按分节符与分页符处理
后端·python
qiqsevenqiqiqiqi19 分钟前
字符串模板
算法
树獭叔叔24 分钟前
Claude Code 工具系统深度剖析:从静态注册到动态发现
后端·aigc·openai
Fcy64829 分钟前
算法基础详解(六)倍增思想与离散化思想
算法·快速幂·离散化·倍增算法