2015年10月15日星期四

Leetcode 146 LRU Cache

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.
Solution 1: Need 2 data structure. One is the dual-linked list like deque. So we can easily rise/add to first and remove last. The other structure is hash table or tree table for fast search hit.
 public class LRUCache {  
   private class Node {  
     private int key;  
     private int val;  
     private Node left,right;  
     public Node(int key, int val) {  
       this.key=key;  
       this.val=val;  
     }  
   }  
   private Node head, tail;  
   private Map<Integer,Node> map;  
   private final int n;  
   public LRUCache(int capacity) {  
     n=capacity;  
     map=new HashMap<>();  
     head=null;  
     tail=null;  
   }  
   public int get(int key) {  
     if (!map.containsKey(key)) return -1;  
     Node x=map.get(key);  
     swim(x);  
     return x.val;  
   }  
   public void set(int key, int value) {  
     if (map.containsKey(key)) {  
       Node x=map.get(key);  
       x.val=value;  
       swim(x);  
     }  
     else {  
       Node x=new Node(key,value);  
       if (head==null) {  
         head=x;  
         tail=x;  
       }  
       else {  
         x.right=head;  
         head.left=x;  
         head=x;  
       }  
       map.put(key,x);  
       if (map.size()>n) {  
         Node pre=tail.left;  
         tail.left=null;  
         pre.right=null;  
         map.remove(new Integer(tail.key));  
         tail=pre;  
       }  
     }  
   }  
   private void swim(Node x) {  
     if (x==head) return;  
     if (x==tail) {  
       tail=x.left;  
       tail.right=null;  
     }  
     else {  
       Node left=x.left;  
       Node right=x.right;  
       left.right=right;  
       right.left=left;  
     }  
     x.left=null;  
     x.right=head;  
     head.left=x;  
     head=x;  
   }  
 }  

没有评论:

发表评论