采用HashMap加上双向链表可以做到get和put的时间复杂度达到O(1)。map里面的value存的就是双向链表的节点(key,value),是相互连接在一起的。
import java.util.HashMap; //双向链表节点 class dulNode{ int key; int val; dulNode next; dulNode pre; public dulNode(int key, int val){ this.key = key; this.val = val; this.next = null; this.pre = null; } } //双向链表 class dulList{ dulNode head; dulNode tail; int size; public dulList(){ head = new dulNode(0, 0); tail = new dulNode(0, 0); head.next = tail; tail.pre = head; size = 0; } public void addFirst(dulNode node){ node.next = head.next; head.next.pre = node; head.next = node; node.pre = head; size ++; } public void remove(dulNode node){ node.next.pre = node.pre; node.pre.next = node.next; size --; } public dulNode removeLast(){ if(tail.pre == head) return null; else{ dulNode last = tail.pre; remove(tail.pre); return last; } } public int size(){ return size; } } class LRUCache { int cap; HashMap<Integer, dulNode> map; dulList list; public LRUCache(int capacity) { this.cap = capacity; map = new HashMap<Integer, dulNode>(); list = new dulList(); } public int get(int key) { if(!map.containsKey(key)){ return -1; } int val = map.get(key).val; put(key, val); return val; } public void put(int key, int value) { dulNode node = new dulNode(key, value); if(map.containsKey(key)){ list.remove(map.get(key)); list.addFirst(node); map.put(key, node); } else{ if(cap == list.size()){ dulNode last = list.removeLast(); map.remove(last.key); //同时在map里面把这个key删除 } list.addFirst(node); map.put(key, node); } } }