标签:
Question:
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.
Analysis:
1 public class Solution { 2 class ListNode { 3 int key, val; 4 ListNode next; 5 6 ListNode(int key, int val) { 7 this.key = key; 8 this.val = val; 9 this.next = null; 10 } 11 } 12 13 14 int capacity; 15 HashMap<Integer, ListNode> map; 16 ListNode dummy, tail; 17 18 // @param capacity, an integer 19 public Solution(int capacity) { 20 this.capacity = capacity; 21 this.map = new HashMap<Integer, ListNode>(); 22 dummy = new ListNode(Integer.MIN_VALUE, -1); 23 tail = dummy; 24 } 25 26 // @return an integer 27 public int get(int key) { 28 if(map.containsKey(key)) { 29 ListNode prev = map.get(key); 30 moveToTail(prev); 31 32 return map.get(key).next.val; 33 }else { 34 return -1; 35 } 36 } 37 38 // @param key, an integer 39 // @param value, an integer 40 // @return nothing 41 public void set(int key, int value) { 42 if(get(key) != -1) { 43 tail.val = value; 44 }else { 45 if(map.size() == capacity) { 46 ListNode removeNode = dummy.next; 47 dummy.next = dummy.next.next; 48 map.remove(removeNode.key); 49 //一定要检查dummy.next,如果capacity是1,不检查的话会出错 50 if(dummy.next != null) { 51 map.put(dummy.next.key, dummy); 52 } 53 } 54 55 ListNode node = new ListNode(key, value); 56 tail.next = node; 57 map.put(key, tail); 58 59 tail = node; 60 } 61 } 62 63 private void moveToTail(ListNode prev) { 64 //if key is at the end of list, do nothing 65 if(prev.next == tail) { 66 return; 67 } 68 69 ListNode temp = prev.next; 70 prev.next = prev.next.next; 71 //这里可以不检查 72 if(prev.next != null) { 73 map.put(prev.next.key, prev); //whenever the structure of list changes, we need to update map 74 } 75 76 tail.next = temp; 77 temp.next = null; 78 map.put(temp.key, tail); //whenever the structure of list changes, we need to update map 79 80 tail = temp; 81 } 82 }
标签:
原文地址:http://www.cnblogs.com/billzhou0223/p/5154503.html