Advertisement
1988coder

146. LRU Cache

Dec 9th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.05 KB | None | 0 0
  1. /*
  2. All operations have O(1) time complexity
  3. Space Complexity : O(capacity)
  4. */
  5. class LRUCache {
  6.     private class Node {
  7.         int key;
  8.         int value;
  9.         Node prev;
  10.         Node next;
  11.        
  12.         public Node(int k, int v) {
  13.             key = k;
  14.             value = v;
  15.             prev = null;
  16.             next = null;
  17.         }
  18.     }
  19.    
  20.     HashMap<Integer, Node> map;
  21.     Node head;
  22.     Node tail;
  23.     int maxCapacity;
  24.  
  25.     public LRUCache(int capacity) {
  26.         map = new HashMap<Integer, Node>();
  27.         head = new Node(0, 0);
  28.         tail = new Node(0, 0);
  29.         head.next = tail;
  30.         tail.prev = head;
  31.         maxCapacity = capacity;
  32.     }
  33.    
  34.     private void addToHead(Node node) {
  35.         node.next = head.next;
  36.         head.next.prev = node;
  37.         node.prev = head;
  38.         head.next = node;
  39.     }
  40.    
  41.     private void deleteNode(Node node) {
  42.         node.next.prev = node.prev;
  43.         node.prev.next = node.next;
  44.         node.prev = null;
  45.         node.next = null;
  46.     }
  47.    
  48.     private void moveToHead(Node node) {
  49.         deleteNode(node);
  50.         addToHead(node);
  51.     }
  52.    
  53.     public int get(int key) {
  54.         if (!map.containsKey(key)) {
  55.             return -1;
  56.         }
  57.        
  58.         Node cur = map.get(key);
  59.         moveToHead(cur);
  60.         return cur.value;
  61.     }
  62.    
  63.     public void put(int key, int value) {
  64.         if (maxCapacity <= 0) {
  65.             return;
  66.         }
  67.        
  68.         if (map.containsKey(key)) {
  69.             Node cur = map.get(key);
  70.             cur.value = value;
  71.             moveToHead(cur);
  72.             return;
  73.         }
  74.        
  75.         if (map.size() == maxCapacity) {
  76.             map.remove(tail.prev.key);
  77.             deleteNode(tail.prev);
  78.         }
  79.        
  80.         Node node = new Node(key, value);
  81.         map.put(key, node);
  82.         addToHead(node);
  83.     }
  84. }
  85.  
  86. /**
  87.  * Your LRUCache object will be instantiated and called as such:
  88.  * LRUCache obj = new LRUCache(capacity);
  89.  * int param_1 = obj.get(key);
  90.  * obj.put(key,value);
  91.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement