[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.node

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.this

 

Subscribe to see which companies asked this questionspa

 
Solution:
 
 1 public class LRUCache 
 2 {
 3     private class Node
 4     {
 5         Node prev;
 6         Node next;
 7         int key;
 8         int value;
 9 
10         public Node(int key, int value) 
11         {
12             this.key = key;
13             this.value = value;
14             this.prev = null;
15             this.next = null;
16         }
17     }
18 
19     private int capacity;
20     private HashMap<Integer, Node> hs = new HashMap<Integer, Node>();
21     private Node head = new Node(-1, -1);
22     private Node tail = new Node(-1, -1);
23 
24     public LRUCache(int capacity) 
25     {
26         this.capacity = capacity;
27         tail.prev = head;
28         head.next = tail;
29     }
30 
31     public int get(int key) 
32     {
33         if( !hs.containsKey(key)) 
34         {
35             return -1;
36         }
37 
38         // remove current
39         Node current = hs.get(key);
40         node_delete(current);
41 
42         // move current to tail
43         move_to_head(current);
44 
45         return hs.get(key).value;
46     }
47 
48     public void set(int key, int value) 
49     {
50         if( get(key) != -1) 
51         {
52             hs.get(key).value = value;
53             return;
54         }
55 
56         if (hs.size() == capacity) 
57         {
58             Node LastNode = tail.prev;
59             hs.remove(LastNode.key);
60             node_delete(LastNode);
61         }
62 
63         Node insert = new Node(key, value);
64         hs.put(key, insert);
65         move_to_head(insert);
66     }
67     private void node_delete(Node current)
68     {
69         current.prev.next = current.next;
70         current.next.prev = current.prev;
71     }
72     private void move_to_head(Node node) 
73     {
74         node.next = head.next;
75         node.next.prev = node;
76         node.prev = head;
77         head.next = node;
78     }
79 }
相關文章
相關標籤/搜索