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

运行结果


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

相关推荐
SuniaWang2 小时前
《Spring AI + 大模型全栈实战》学习手册系列· 专题二:《Milvus 向量数据库:从零开始搭建 RAG 系统的核心组件》
java·人工智能·分布式·后端·spring·架构·typescript
Klong.k2 小时前
判断是不是素数题目
数据结构·算法
QQsuccess2 小时前
AI全体系保姆级详讲——第一部分:了解AI基本定义
人工智能·算法
张小洛2 小时前
Spring 常用类深度剖析(工具篇 02):ReflectionUtils——优雅操作反射的利器
java·后端·spring·工具类·spring常用类
_日拱一卒2 小时前
LeetCode:移动零
算法·leetcode·职场和发展
夕颜1112 小时前
Skill 与 MCP Function:傻傻分不清楚?
后端
A923A2 小时前
【洛谷刷题 | 第四天】
算法·前缀和·贪心·洛谷·差分
古城小栈2 小时前
Go 底层代码的完整分类
开发语言·后端·golang
码界奇点2 小时前
基于Spring Boot和MyBatis的图书管理系统设计与实现
spring boot·后端·车载系统·毕业设计·mybatis·源代码管理
耳冉鹅2 小时前
Go无锁共享内存环形缓冲区设计
开发语言·golang