146. LRU Cache 「LRU 缓存机制」

设计并实现一个数据结构:最久使用缓存(LRU)。它应当支持 getput 操作。

  • get(key) – 如果键存在缓存中,获取键的值(值总是正数),否则返回 -1。
  • put(key, value) – 设置键对应的值,如果不存在键,则插入键和值。当缓存容量满时,在插入新键值对前应当使最久使用的键值对无效。

此缓存将会使用正数容量初始化。

举例:

LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.put(4, 4);    // evicts key 1
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4
/*
 * 146. LRU Cache
 * https://leetcode.com/problems/lru-cache/
 * https://www.whosneo.com/146-lru-cache/
 */

import java.util.Hashtable;

class LRUCache {
    private Hashtable<Integer, Node> cache = new Hashtable<>();
    private int size;
    private int capacity;
    private Node head, tail;

    public static void main(String[] args) {
        LRUCache cache = new LRUCache(2);
        cache.put(1, 1);
        cache.put(2, 2);
        System.out.println(cache.get(1));
        cache.put(3, 3);
        System.out.println(cache.get(2));
        cache.put(4, 4);
        System.out.println(cache.get(1));
        System.out.println(cache.get(3));
        System.out.println(cache.get(4));
    }

    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) {
        Node node = cache.get(key);

        if (node == null) {
            node = new Node();
            node.key = key;
            node.value = value;
            cache.put(key, node);
            addNode(node);
            size++;
            if (size > capacity) {
                node = popTail();
                cache.remove(node.key);
                size--;
            }
        } else {
            node.value = value;
            moveToHead(node);
        }
    }

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

    private Node popTail() {
        Node node = tail.prev;
        removeNode(node);
        return node;
    }

    private void addNode(Node node) {
        node.next = head.next;
        node.prev = head;

        head.next.prev = node;
        head.next = node;
    }

    private void removeNode(Node node) {
        node.next.prev = node.prev;
        node.prev.next = node.next;
    }

    static class Node {
        int key;
        int value;
        Node prev;
        Node next;
    }
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注