146. LRU 缓存

力扣链接:. - 力扣(LeetCode)

思路:双向链表用来维护"最近最少使用",hashmap用来比较方便的根据key取value

java 复制代码
class LRUCache {
    class Node{
        Node pre;
        Node next;
        int key, val;
        Node(){}
        Node(int key, int val){
            this.key = key;
            this.val = val;
        }
    }
    private int capacity;
    private Map<Integer, Node> cache;
    //分别指向头尾节点,便于在头部插入和在尾部删除节点
    private Node head, tail;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.cache = new HashMap<>();
        head = new Node();
        tail = new Node();
        head.next = tail;
        tail.pre = head;
    }
    
    public int get(int key) {
        Node node = cache.get(key);
        if(node == null) return -1;
        //如果存在,则移到头部
        moveToHead(node);
        return node.val;
    }
    
    public void put(int key, int value) {
        Node node = cache.get(key);
        if(node != null) {
            node.val = value;
            moveToHead(node);
        } else {
            Node newNode = new Node(key, value);
            //如果容量超了,先移除
            if(cache.size()==capacity){
                Node realTail = tail.pre;
                removeNode(realTail);
                cache.remove(realTail.key);
            }
            addHead(newNode);
            cache.put(key, newNode);
        }
    }

    private void moveToHead(Node node) {
        removeNode(node);
        addHead(node);
    }

    private void removeNode(Node node) {
        Node nextNode = node.next;
        Node preNode = node.pre;
        preNode.next = nextNode;
        nextNode.pre = preNode;
    }

    private void addHead(Node node) {
        node.next = head.next;
        head.next.pre = node;
        node.pre = head;
        head.next = node;
    }
}
相关推荐
明月与玄武7 小时前
前端缓存战争:回车与刷新按钮的终极对决!
前端·缓存·回车 vs 点击刷新
JH30738 小时前
《Redis 经典应用场景(一):缓存、分布式锁与限流》
redis·分布式·缓存
苦学编程的谢8 小时前
Redis_4_常见命令(完)+认识数据类型和编码方式
数据库·redis·缓存
大G的笔记本11 小时前
高频 Redis 面试题答案解析
数据库·redis·缓存
m0_7482480213 小时前
Redis的数据淘汰策略解读
数据库·redis·缓存
Freed&14 小时前
《Nginx进阶实战:反向代理、负载均衡、缓存优化与Keepalived高可用》
nginx·缓存·负载均衡
Irene199115 小时前
前端缓存技术和使用场景
前端·缓存
小吕学编程16 小时前
缓存三部曲:从线程到分布式
缓存
LB211216 小时前
Redis黑马点评 Feed流
数据库·redis·缓存