手撕LRU缓存——LinkedHashMap简易源码

题目链接:https://leetcode.cn/problems/lru-cache/description/?envType=study-plan-v2&envId=top-100-liked

原理非常简单,一个双端链表配上一个hash表。

首先我们要知道什么是LRU就是最小使用淘汰。怎么淘汰,链表尾部就是最不常用的直接删除,最近使用过的就移动到链表头部。要查找就利用hash表进行映射查找。

代码:

java 复制代码
class LRUCache {
    //需要定义的双端链表节点
    //哈希表
    class Node{
        int key;
        int value;
        Node prev;
        Node next;
        public Node() {}
        public Node(int _key,int _value) {
            key = _key;
            value = _value;
        }
    }
    private Map<Integer,Node > cache = new HashMap<>();
    private int size;
    private int capacity;
    private Node head,tail;
    public LRUCache(int capacity) {
        this.size = 0;
        this.capacity = capacity;
        head = new Node();
        tail = new Node();
        head.next = tail;
        tail.prev = head;
    }
    
    public int get(int key) {
        Node node = cache.get(key);
        if(node == null) 
            return -1;
        moveToHead(node);
        return node.value;
    }
    
    public void put(int key, int value) {
        //如果存在
        if(cache.containsKey(key)){
            Node t = cache.get(key);
            t.value = value;
            moveToHead(t);
        }else{
            //如果不存在
            size++;
            if(size>capacity){
                cache.remove(tail.prev.key);
                //System.out.println(tail.prev.key);
                moveTail();
                size--;
            }
            Node node = new Node(key,value);
            Node temp = head.next;
            head.next = node;
            node.prev = head;
            temp.prev = node;
            node.next = temp;
            cache.put(key,node);
        }
    }

    public void moveToHead(Node node){
        //本身删除了
        Node qian = node.prev;
        qian.next = node.next;
        node.next.prev = qian;
        //再插到头部
        Node temp = head.next;
        head.next = node;
        node.prev = head;
        temp.prev = node;
        node.next = temp;
    }

    public void moveTail(){
        Node temp = tail.prev.prev;
        temp.next = tail;
        tail.prev = temp;
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */
相关推荐
九皇叔叔16 小时前
RHEL9.8 配置本地镜像仓库
android·java·缓存
智脑API平台19 小时前
Codex 国内使用会封号吗?账号安全、中转站和合规边界说明
数据库·redis·缓存
迷途呀21 小时前
新闻头条后端:新闻缓存模块
前端·redis·python·缓存·fastapi
●VON21 小时前
HarmonyKit | 鸿蒙开发:hvigor 构建系统命令行与缓存机制详解
缓存·华为·交互·harmonyos·鸿蒙
数据知道21 小时前
DNS 安全攻防:缓存投毒、DNS 隧道与检测实战
安全·网络安全·缓存·缓存投毒
吴声子夜歌1 天前
Redis 5.x——布隆过滤器
数据库·redis·缓存
斯蒂文6682 天前
[MAF预定义ChatClient中间件-03]CachingChatClient——利用缓存省钱省时间
缓存·中间件
難釋懷2 天前
Nginx浏览器强制缓存
运维·nginx·缓存
诚信定制8392 天前
如何启动 Redis 服务:详细步骤指南
数据库·redis·缓存
cxr8282 天前
缓存策略探测实验 — 综合执行方案
java·开发语言·缓存