MCPcopy Create free account
hub / github.com/codedecks-in/LeetCode-Solutions / LRUCache

Class LRUCache

Java/LRU-Cache.java:9–84  ·  view source on GitHub ↗

LRU Cache Logic : maintain doubly linked List for insertion at head and deletion from tail and maintain hashmap of key as key and value as node. Node consists of key, value, prev and next pointers. Runtime: 16 ms Memory Usage: 47.9 MB

Source from the content-addressed store, hash-verified

7*/
8
9class LRUCache {
10
11 final Node head = new Node();
12 final Node tail = new Node();
13 int capacity;
14 Map<Integer, Node> map;
15
16 public LRUCache(int capacity) {
17 map = new HashMap(capacity);
18 this.capacity = capacity;
19 head.next = tail;
20 tail.prev = head;
21 }
22
23 public int get(int key) {
24 int result = -1;
25 Node node = map.get(key);
26 if(node!=null)
27 {
28 remove(node);
29 add(node);
30 result = node.val;
31 }
32 return result;
33 }
34
35 public void put(int key, int value) {
36 Node node = map.get(key);
37 if(node!=null)
38 {
39 remove(node);
40 node.val = value;
41 add(node);
42 }
43 else{
44 if(map.size() == capacity)
45 {
46 map.remove(tail.prev.key);
47 remove(tail.prev);
48 }
49 Node new_node = new Node();
50
51 new_node.key = key;
52 new_node.val = value;
53 map.put(key, new_node);
54 add(new_node);
55 }
56 }
57
58 public void add(Node node)
59 {
60 Node head_next = head.next;
61 node.next = head_next;
62 head_next.prev = node;
63 head.next = node;
64 node.prev = head;
65
66 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected