首页 > 代码库 > [LeetCode]146 LRU Cache
[LeetCode]146 LRU Cache
https://oj.leetcode.com/problems/lru-cache/
http://blog.csdn.net/linhuanmars/article/details/21310633
public class LRUCache { public LRUCache(int capacity) { map = new HashMap<>(); head = null; tail = null; this.size = 0; this.capacity = capacity; } public int get(int key) { Node hit = map.get(key); if (hit == null) return -1; // Remove hit from list. removeNodeFromList(hit); // Add hit to the head addNodeToHead(hit); return hit.value; } // Remove some node from the list private void removeNodeFromList(Node n) { if (n == null) return; Node pre = n.pre; Node next = n.next; if (pre == null) // node is head head = next; else pre.next = next; if (next == null) // node is tail tail = pre; else next.pre = pre; n.pre = null; n.next = null; size --; } // Add some node to head. // The node doesn‘t belongs to the list. private void addNodeToHead(Node n) { if (n == null) return; if (head == null) // Empty list { head = n; tail = n; } else { n.next = head; head.pre = n; head = n; } size ++; } public void set(int key, int value) { Node hit = map.get(key); if (hit != null) { hit.value = value; map.put(key, hit); removeNodeFromList(hit); addNodeToHead(hit); } else { hit = new Node(key, value); map.put(key, hit); if (size == capacity) { map.remove(tail.key); removeNodeFromList(tail); } addNodeToHead(hit); } } public void remove(int key) { Node hit = map.get(key); if (hit == null) return; // Remove from map map.remove(hit.key); // Remove from list removeNodeFromList(hit); } private Node head; private Node tail; private Map<Integer, Node> map; private int size; private int capacity; // A doubly linked list node. private static class Node { int key; int value; Node next; Node pre; public Node(int key, int value) { this.key = key; this.value = value; this.next = null; this.pre = null; } } }
[LeetCode]146 LRU Cache
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。