手撕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);
 */
相关推荐
赖small强12 分钟前
【Linux 内存管理】深入解析 Linux Cache Line 的原理、价值及 MIPS CPU 处理机制
linux·缓存·内存对齐·cache line
卿雪18 分钟前
Redis 数据过期删除和内存淘汰策略
数据库·redis·缓存
C++业余爱好者1 小时前
Springboot中的缓存使用
spring boot·后端·缓存
武子康1 小时前
Java-185 Guava Cache 实战:删除策略、过期机制与常见坑全梳理
java·spring boot·redis·spring·缓存·guava·guava cache
only-qi12 小时前
Redis如何应对 Redis 大 Key 问题
数据库·redis·缓存
天生励志12315 小时前
Redis 安装部署
数据库·redis·缓存
武帝为此18 小时前
【Redis 数据库介绍】
数据库·redis·缓存
铁锚18 小时前
Redis中KEYS命令的潜在风险与遍历建议
数据库·redis·缓存
程序员果子19 小时前
零拷贝:程序性能加速的终极奥秘
linux·运维·nginx·macos·缓存·centos
可爱の小公举20 小时前
Redis技术体系全面解析
数据库·redis·缓存