題目連接java
整體思路,是雙向鏈表和哈希表搭配使用,同時要記錄一個LRU的最大容量Capacity。
雙向鏈表尾部記錄最新使用過的記錄,頭部記錄的是最久沒有使用過的記錄。
具體來講,對於put操做:node
對於get操做:git
完整代碼見:程序員
public static class LRUCache { public static class Node { public int key; public int value; public Node last; public Node next; public Node(int key, int value) { this.key = key; this.value = value; } } public static class DoubleLinkedList { public Node head; public Node tail; public DoubleLinkedList() { head = null; tail = null; } public void moveToLast(Node node) { if (tail == node) { return; } if (head == node) { head = node.next; head.last = null; } else { node.last.next = node.next; node.next.last = node.last; } node.last = tail; node.next = null; tail.next = node; tail = node; } public void addLast(Node node) { if (head == null) { head = node; tail = node; } if (tail != null) { tail.next = node; node.last = tail; tail = node; } } } private HashMap<Integer, Node> map; private DoubleLinkedList list; private final int capacity; public LRUCache(int capacity) { this.map = new HashMap<>(); this.list = new DoubleLinkedList(); this.capacity = capacity; } /*["LRUCache","put","put","get","put","get","put","get","get","get"] [[2],[1,1],[2,2],[1],[3,3],[2],[4,4],[1],[3],[4]] [null,null,null,1,null,2,null,1,3,4]*/ // note get值後,須要把這個值設置爲最新的未使用的過的值 public int get(int key) { if (map.containsKey(key)) { Node node = map.get(key); list.moveToLast(node); return node.value; } return -1; } public void put(int key, int value) { if (map.containsKey(key)) { Node old = map.get(key); old.value = value; list.moveToLast(old); } else { if (map.size() == capacity) { map.remove(list.head.key); list.head.value = value; list.head.key = key; map.put(key, list.head); list.moveToLast(list.head); } else { Node node = new Node(key, value); map.put(key, node); list.addLast(node); } } } }
算法和數據結構筆記github