标签:
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and set
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.set(key, value)
- Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
1 public class Solution { 2 3 private int cacheSize; 4 private HashMap<Integer, Entry> map;// 缓存容器 5 private int currentSize; 6 private Entry first;// 链表头 7 private Entry last;// 链表尾 8 9 public Solution(int i) { 10 currentSize = 0; 11 cacheSize = i; 12 map = new HashMap<Integer, Entry>(i);// 缓存容器 13 } 14 15 /* 16 public static void main(String[] args) { 17 Solution s = new Solution(2); 18 // [set(2,1),set(1,1),get(2),set(4,1),get(1),get(2)] 19 s.set(2, 1); 20 s.set(1, 1); 21 System.out.println(s.get(2)); 22 s.set(4, 1); 23 System.out.println(s.get(1)); 24 System.out.println(s.get(2)); 25 System.out.println(""); 26 } 27 */ 28 29 public int get(int key) { 30 Entry node = map.get(key); 31 if (node != null) { 32 moveToHead(node); 33 return node.value; 34 } else { 35 return -1; 36 } 37 } 38 39 public void remove(int key) { 40 Entry node = map.get(key); 41 // 在链表中删除 42 if (node != null) { 43 if (node.prev != null) node.prev.next = node.next; 44 if (node.next != null) node.next.prev = node.prev; 45 if (last == node) last = node.prev; 46 if (first == node) first = node.next; 47 } 48 // 在HashMap中删除 49 map.remove(key); 50 } 51 52 private void moveToHead(Entry node) { 53 if (node == first) return; 54 if (node.prev != null) node.prev.next = node.next; 55 if (node.next != null) node.next.prev = node.prev; 56 if (node == last) last = node.prev; 57 if (first != null) { 58 node.next = first; 59 first.prev = node; 60 } 61 first = node; 62 node.prev = null; 63 if (last == null) last = first; 64 } 65 66 public void set(int key, int value) { 67 Entry node = map.get(key); 68 69 if (node == null) { 70 // 缓存容器是否已经超过大小. 71 if (currentSize >= cacheSize) { 72 map.remove(last.key); 73 removeLast(); 74 } else { 75 currentSize++; 76 } 77 node = new Entry(); 78 } 79 node.value = value; 80 node.key = key; 81 // 将最新使用的节点放到链表头,表示最新使用的. 82 moveToHead(node); 83 map.put(key, node); 84 } 85 86 private void removeLast() { 87 // 链表尾不为空,则将链表尾指向null. 删除连表尾(删除最少使用的缓存对象) 88 if (last != null) { 89 if (last.prev != null) { 90 last.prev.next = null; 91 } else { 92 first = null; 93 } 94 last = last.prev; 95 } 96 } 97 } 98 99 class Entry { 100 Entry prev;// 前一节点 101 Entry next;// 后一节点 102 int value;// 值 103 int key;// 键 104 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5674971.html