经典算法 - LRU 缓存

282

题目

LC-146. LRU缓存机制

运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。

获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。

进阶:

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

示例:

LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // 返回  1
cache.put(3, 3);    // 该操作会使得密钥 2 作废
cache.get(2);       // 返回 -1 (未找到)
cache.put(4, 4);    // 该操作会使得密钥 1 作废
cache.get(1);       // 返回 -1 (未找到)
cache.get(3);       // 返回  3
cache.get(4);       // 返回  4

思路

1. LinkedHashMap

自带实现了 LRU 序列,重载删除策略,和指定初始化的 LRU 顺序为 true 即可

  • 时间复杂度:O(1)
  • 空间复杂度:O(n)
import java.util.*;

class LRUCache {

    class Cache<K, V> extends LinkedHashMap<K, V> {
        
        private int capacity;

        public Cache(int capacity) {
            super(capacity, 0.75f, true);
            this.capacity = capacity;
        }

        @Override
        protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
            return size() > this.capacity;
        }
    }

    private Cache<Integer, Integer> cache;


    public LRUCache(int capacity) {
        this.cache = new Cache<>(capacity);
    }
    
    public int get(int key) {
        if (this.cache.containsKey(key)) {
            return this.cache.get(key);
        }
        return -1;
    }
    
    public void put(int key, int value) {
        this.cache.put(key, value);
    }
}

2. 双向链表 + HashMap

内部维护一个 LRU 顺序的双向链表,使用 HashMap 可以在 O(1) 时间复杂度内找到该节点

做这个首先如何维护一个 LRU 序列的链表?可以通过一个双向链表来维护:

  • 新节点插入到链表尾部
  • 访问了节点,将节点移动到链表尾部(先删除,再插入到链表尾部)
  • 淘汰节点(到达指定的容量时),总是淘汰链表头节点,也就是首节点

于是,需要额外实现删除双向链表节点 deleteNode() 和插入链表节点到尾部的方法 insertNode() 即可,如下

class LRUCache {

    class Node {
        int key;
        int val;
        Node next;
        Node prev;
        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    private int capacity;

    private Node head;

    private Node tail;

    private Map<Integer, Node> cache;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.cache = new HashMap<>(capacity);
    }

    public int get(int key) {
        if (cache.containsKey(key)) {
            // 更新链表顺序
            Node node = cache.get(key);
            deleteNode(node);
            insertNode(node);
            return node.val;
        }
        return -1;
    }

    public void put(int key, int value) {
        // 已包含 / 未包含且容量不够 / 未包含容量够
        if (cache.containsKey(key)) {
            Node node = cache.get(key);
            // 更新 cache
            node.val = value;
            // 更新链表顺序
            deleteNode(node);
            insertNode(node);
        } else {
            // 超出容量
            if (cache.size() == capacity) {
                // 删除头部节点
                cache.remove(head.key);
                deleteNode(head);
            }
            Node node = new Node(key, value);
            cache.put(key, node);
            insertNode(node);
        }
    }

    private void deleteNode(Node node) {
        // 空节点不可执行删除
        if ((head == tail) && (head == null)) {
            return;
        }
        // 一个节点 / 节点为 head / 节点为 tail / 节点为中间
        if (head == tail) {
            head = null;
            tail = null;
        } else if (node == head) {
            head.next.prev = null;
            head = head.next;
        } else if (node == tail) {
            tail.prev.next = null;
            tail = tail.prev;
        } else {
            node.prev.next = node.next;
            node.next.prev = node.prev;
        }
    }

    private void insertNode(Node node) {
        // 第一个节点 / 非第一个节点的插入,插入到尾部
        if (head == null) {
            head = node;
            tail = node;
        } else {
            tail.next = node;
            node.prev = tail;
            tail = node;
        }
    }
}

总结

经典的数据结构设计题,LRU 缓存,没事刷一下,检测码力