【leetcode】146.LRU 缓存机制 (Java)

题目描述

运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制 。实现 LRUCache 类:

  • LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
  • int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
  • void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。

进阶:你是否可以在 O(1) 时间复杂度内完成这两种操作?

示例:

输入
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
输出
[null, null, null, 1, null, -1, null, -1, 3, 4]

解释
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // 缓存是 {1=1}
lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
lRUCache.get(1);    // 返回 1
lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
lRUCache.get(2);    // 返回 -1 (未找到)
lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
lRUCache.get(1);    // 返回 -1 (未找到)
lRUCache.get(3);    // 返回 3
lRUCache.get(4);    // 返回 4

提示:

  • 1 <= capacity <= 3000
  • 0 <= key <= 10000
  • 0 <= value <= 105
  • 最多调用 2 * 105 次 get 和 put

题解

可以get,put 所以要使用到hashmap。要突出顺序,要使用到链表。所以最后用哈希链表来实现LRU缓存机制。
1、哈希链表节点,必须是双向链表,才能保证删除的复杂度是O(1)。

class Node{
        private int key;
        private int value;
        Node pre, next;
        public Node(){}
        public Node(int key, int value){
            this.key = key;
            this.value = value;
        }

        public int getKey() {return this.key;}
        public int getValue() {return this.value;}
        public void setValu(int value) {this.value = value;}
    }

2、初始化:count用来记录当前有多少个节点。capacity表示容量。新建虚拟头节点head,尾节点tail简化处理时的逻辑。map用来实现时间复杂度为O(1)的查找
3、查找:利用map.get(key)查找到节点,如果查找到节点,把当前节点抽取出链表,插入链表头部。如果没有查找到节点,返回-1。
4、插入:

  • 如果map中已经有了当前的key,利用map.get(key)查找到节点,把当前节点抽取出链表,修改节点的值,插入链表头部。
  • 如果map中没有,新建一个节点,插入链表头部,count++。此时如果count > capacity。 删除最后一个节点(也就是tail之前的节点),并删除map之中保存的节点,count–。
class LRUCache {
    class Node{
        private int key;
        private int value;
        Node pre, next;
        public Node(){}
        public Node(int key, int value){
            this.key = key;
            this.value = value;
        }

        public int getKey() {return this.key;}
        public int getValue() {return this.value;}
        public void setValu(int value) {this.value = value;}
    }

    private int count;
    private int capacity;
    Map<Integer, Node> map;
    Node head;
    Node tail;

    public LRUCache(int capacity) {
        count = 0;
        this.capacity = capacity;
        map = new HashMap<>();
        head = new Node();
        tail = new Node();
        head.next = tail;
        tail.pre = head;
    }
    
    public int get(int key) {
        if (map.containsKey(key)){
            Node node = map.get(key);
            //抽取出当前的节点
            node.next.pre = node.pre;
            node.pre.next = node.next;
            //插入到头节点之后
            node.next = head.next;
            head.next = node;
            node.next.pre = node;
            node.pre = head;
            return node.getValue();
        }else{
            return -1;
        }
    }
    
    public void put(int key, int value) {
        if (map.containsKey(key)){
            Node node = map.get(key);
            //抽取出当前的节点
            node.next.pre = node.pre;
            node.pre.next = node.next;
            //插入到头节点之后
            node.next = head.next;
            head.next = node;
            node.next.pre = node;
            node.pre = head;
            //修改当前节点的值,添加到map之中
            node.setValu(value);
            map.put(key, node);
        }else{
            count++;
            //新建节点,插入头节点之后
            Node node = new Node(key, value);
            node.next = head.next;
            head.next = node;
            node.next.pre = node;
            node.pre = head;
            map.put(key, node);
            if (count > capacity){
                //删除最后一个节点,并且在map中移除
                int delKey = tail.pre.getKey();
                tail.pre = tail.pre.pre;
                tail.pre.next = tail;
                map.remove(delKey);
                count--;
            }
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
LRU(Least Recently Used)缓存机制是一种常见的缓存淘汰策略,它会将最近最少使用的缓存数据淘汰出去,从而保持缓存的容量在一定的范围内。 在 Java 中,我们可以使用 LinkedHashMap 类来实现 LRU 缓存机制。LinkedHashMap 是一种哈希表和链表实现的有序映射表,它允许我们按照元素的插入顺序或访问顺序进行遍历。我们可以通过设置 accessOrder 参数为 true 来启用按访问顺序排序。 下面是一份简单的 Java 实现代码: ```java import java.util.LinkedHashMap; import java.util.Map; public class LRUCache<K, V> extends LinkedHashMap<K, V> { private int capacity; public LRUCache(int capacity) { super(capacity, 0.75f, true); this.capacity = capacity; } protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > capacity; } } ``` 在上面的代码中,我们继承了 LinkedHashMap 类,并在构造函数中调用了父类的构造函数,同时设置 accessOrder 为 true。我们还实现了 removeEldestEntry 方法,该方法会在每次插入元素时被调用,如果当前缓存的元素数量超过了设定的容量,就会将最老的元素删除。 使用该 LRU 缓存类的示例代码: ```java LRUCache<Integer, Integer> cache = new LRUCache<>(2); cache.put(1, 1); cache.put(2, 2); System.out.println(cache.get(1)); // 输出 1 cache.put(3, 3); System.out.println(cache.get(2)); // 输出 null cache.put(4, 4); System.out.println(cache.get(1)); // 输出 null System.out.println(cache.get(3)); // 输出 3 System.out.println(cache.get(4)); // 输出 4 ``` 在上面的示例代码中,我们创建了一个容量为 2 的 LRU 缓存,并且按顺序插入了三个元素。由于容量只有 2,因此最后插入的元素 4 会将元素 1 淘汰出缓存,而元素 2 虽然是最近使用的,但是由于已经被淘汰出缓存,因此返回的值为 null。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值