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

运行结果


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

相关推荐
m0_531237171 分钟前
C语言-while循环,continue/break,getchar()/putchar()
java·c语言·算法
kong79069283 分钟前
SpringBoot原理
java·spring boot·后端
那我掉的头发算什么7 分钟前
【图书管理系统】基于Spring全家桶的图书管理系统(下)
java·数据库·spring boot·后端·spring·mybatis
一条大祥脚33 分钟前
KMP原理+例题
算法
追随者永远是胜利者10 小时前
(LeetCode-Hot100)20. 有效的括号
java·算法·leetcode·职场和发展·go
瓦特what?11 小时前
快 速 排 序
数据结构·算法·排序算法
niuniudengdeng11 小时前
基于时序上下文编码的端到端无文本依赖语音分词模型
人工智能·数学·算法·概率论
hetao173383711 小时前
2026-02-13~16 hetao1733837 的刷题记录
c++·算法
毅炼11 小时前
Java 集合常见问题总结(3)
java·开发语言·后端
你的冰西瓜13 小时前
2026春晚魔术揭秘——变魔法为物理
算法