【算法】LRU Cache

该代码实现了一个LRU(最近最少使用)缓存机制,使用了HashMap存储键值对,并通过双向链表维护访问顺序。当缓存满时,最近最少使用的项将被移除。get方法首先检查键是否存在,然后更新其在链表中的位置。put方法插入或更新键值对,并在超出容量时删除最不常使用的项。
摘要由CSDN通过智能技术生成

public class LRUCache {

    private class Node {

        public int key;

        public int value;

        public Node pre;

        public Node next;

    };

    

    private HashMap<Integer, Node> map;

    // 保护结点

    private Node head;

    private Node tail;

    private int capacity;

    

    public LRUCache(int capacity) {

        this.capacity = capacity;

        this.map = new HashMap<Integer, Node>();

        // 建立带有保护结点的空双向链表

        head = new Node();

        tail = new Node();

        head.next = tail;

        tail.pre = head;

    }

    

    public int get(int key) {

        if (!this.map.containsKey(key)) return -1;

        Node node = map.get(key);

        // 从链表和map中删掉

        this.removeFromList(node);

        // 重新插入到map、链表头部,维护时间顺序

        this.insertToListHead(node.key, node.value);

        return node.value;

    }

    

    public void put(int key, int value) {

        if (this.map.containsKey(key)) {

            Node node = this.map.get(key);

            // 从链表中删掉

            this.removeFromList(node);

            // 重新插入到头部,维护时间顺序

            this.insertToListHead(key, value);

        } else {

            // 在链表中插入新结点,返回新结点引用

            this.insertToListHead(key, value);

        }

        if (this.map.size() > this.capacity) {

            this.removeFromList(tail.pre);

        }

    }

    private void removeFromList(Node node) {

        node.pre.next = node.next;

        node.next.pre = node.pre;

        this.map.remove(node.key);

    }

    private Node insertToListHead(int key, int value) {

        Node node = new Node();

        node.key = key;

        node.value = value;

        // node与head的下一个点之间建立联系

        node.next = head.next;

        head.next.pre = node;

        // node与head之间建立联系

        node.pre = head;

        head.next = node;

        // 建立映射关系

        this.map.put(key, node);

        return node;

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值