[146 LRU缓存](https://leetcode.cn/problems/lru-cache/)

时间:2024-12-17 07:09:44
class LRUCache { private int size; private int capacity; private Map<Integer, Node> cache = new HashMap<>(); private Node head; private Node tail; public LRUCache(int capacity) { this.capacity = capacity; this.size = 0; this.head = new Node(); this.tail = new Node(); this.head.next = this.tail; this.tail.prev = this.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(key, value); cache.put(key, node); addToHead(node); size++; if (size > capacity) { Node tail = removeTail(); cache.remove(tail.key); size--; } } node.value = value; moveToHead(node); } private void addToHead(Node node) { node.prev = head; node.next = head.next; head.next.prev = node; head.next = node; } private void removeNode(Node node) { node.prev.next = node.next; node.next.prev = node.prev; } private void moveToHead(Node node) { removeNode(node); addToHead(node); } private Node removeTail() { Node res = tail.prev; removeNode(res); return res; } class Node { int key; int value; Node prev; Node next; public Node(int key, int value) { this.key = key; this.value = value; } public Node() { } } }