// LRU缓存机制 // 使用哈希表 + 双向链表(维护使用的频率) class LRUCache { class DoubleLinkedNode { int key; int value; DoubleLinkedNode prev; DoubleLinkedNode next; public DoubleLinkedNode() {} public DoubleLinkedNode(int key, int value) { this.key = key; this.value = value; } } int size; int capacity; DoubleLinkedNode head; // 头结点(起到连接作用) DoubleLinkedNode tail; // 尾节点(起到连接作用) Map<Integer, DoubleLinkedNode> cache = new HashMap<>(); // 起到缓存的作用 public LRUCache(int capacity) { this.size = 0; this.capacity = capacity; head = new DoubleLinkedNode(); tail = new DoubleLinkedNode(); head.next = tail; tail.prev = head; } public int get(int key) { DoubleLinkedNode node = cache.get(key); if (node == null) { return -1; // 不存在 返回-1 } moveToHead(node); // 刚查询过,移动到头部 return node.value; } // 移动到头部(删除节点 在头部增加节点) public void moveToHead(DoubleLinkedNode node) { removeNode(node); addToHead(node); } // 删除节点 public void removeNode(DoubleLinkedNode node) { node.prev.next = node.next; node.next.prev = node.prev; } // 增加节点到头部 public void addToHead(DoubleLinkedNode node) { node.prev = head; node.next = head.next; head.next = node; node.next.prev = node; } // 删除尾部节点 public DoubleLinkedNode removeTail() { DoubleLinkedNode node = tail.prev; removeNode(node); return node; } public void put(int key, int value) { DoubleLinkedNode node = cache.get(key); if (node == null) { DoubleLinkedNode newNode = new DoubleLinkedNode(key, value); cache.put(key, newNode); addToHead(newNode); size++; if (size > capacity) { // 删除尾部元素 DoubleLinkedNode tail = removeTail(); // 删除链表尾部 cache.remove(tail.key); size--; } } else { node.value = value; // moveToHead(node); // 移动到头部 } } } /** * Your LRUCache object will be instantiated and called as such: * LRUCache obj = new LRUCache(capacity); * int param_1 = obj.get(key); * obj.put(key,value); */
标签:node,int,DoubleLinkedNode,value,next,LRU,key From: https://www.cnblogs.com/xiazhenbin/p/16729075.html