146. LRU Cache
阿新 • • 發佈:2017-10-17
logs pac ++ pri capacity private r+ csharp sha
class LRUCache { class DNode{ public int val; public int key; public DNode pre; public DNode next; public DNode(int k, int v){ key=k; val=v; } } private Map<Integer, DNode> map=new HashMap<Integer, DNode>(); private DNode head=new DNode(0,0); private DNode tail=new DNode(0,0); private int cap=0; private int cur=0; private void add(DNode node){ node.pre=head; node.next=head.next; node.pre.next=node; node.next.pre=node; } private void remove(DNode node){ node.pre.next=node.next; node.next.pre=node.pre; } private void move(DNode node){ remove(node); add(node); } public LRUCache(int capacity) { cap=capacity; cur=0; head.next=tail; tail.next=head; } public int get(int key) { if(!map.containsKey(key)) return -1; DNode node=map.get(key); move(node); return node.val; } public void put(int key, int value) { if(map.containsKey(key)) { DNode node=map.get(key); node.val=value; move(node); } else { DNode node=new DNode(key,value); add(node); map.put(key,node); if(cur<cap) cur++; else { DNode last=tail.pre; remove(last); map.remove(last.key); } } } }
146. LRU Cache