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

运行结果


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

相关推荐
a努力。2 小时前
得物Java面试被问:Kafka的零拷贝技术和PageCache优化
java·开发语言·spring·面试·职场和发展·架构·kafka
2501_944521592 小时前
Flutter for OpenHarmony 微动漫App实战:骨架屏加载实现
android·开发语言·javascript·数据库·redis·flutter·缓存
郭涤生2 小时前
AWB算法基础理解
人工智能·算法·计算机视觉
hetao17338372 小时前
2026-01-21~22 hetao1733837 的刷题笔记
c++·笔记·算法
时艰.2 小时前
Redis 核心知识点归纳与详解
数据库·redis·缓存
Hcoco_me2 小时前
大模型面试题91:合并访存是什么?原理是什么?
人工智能·深度学习·算法·机器学习·vllm
2501_901147832 小时前
零钱兑换——动态规划与高性能优化学习笔记
学习·算法·面试·职场和发展·性能优化·动态规划·求职招聘
狐574 小时前
2026-01-22-LeetCode刷题笔记-3507-移除最小数对使数组有序I
笔记·leetcode
充值修改昵称4 小时前
数据结构基础:B树磁盘IO优化的数据结构艺术
数据结构·b树·python·算法