-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy path146-lru-cache.java
105 lines (95 loc) · 2.41 KB
/
146-lru-cache.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
class Node {
int key;
int val;
Node prev;
Node next;
public Node(int key, int val) {
this.key = key;
this.val = val;
}
}
class Dll {
Node head;
Node tail;
public Dll() {
head = new Node(- 1, - 1);
tail = new Node(- 1, - 1);
head.next = tail;
tail.prev = head;
}
public void append(Node node) {
Node prevNode = tail.prev;
Node nextNode = tail;
prevNode.next = node;
node.prev = prevNode;
node.next = nextNode;
nextNode.prev = node;
return;
}
public void update(Node node) {
Node prevNode = node.prev;
Node nextNode = node.next;
prevNode.next = nextNode;
nextNode.prev = prevNode;
this.append(node);
return;
}
public Node popleft() {
Node prevNode = head;
Node node = prevNode.next;
Node nextNode = node.next;
prevNode.next = nextNode;
nextNode.prev = prevNode;
return node;
}
}
class LRUCache {
int capacity;
Dll dll;
HashMap<Integer, Node> keyToNode;
public LRUCache(int capacity) {
this.capacity = capacity;
dll = new Dll();
keyToNode = new HashMap<>();
}
public int get(int key) {
if (!keyToNode.containsKey(key)) {
return - 1;
}
Node node = keyToNode.get(key);
dll.update(node);
return node.val;
}
public void put(int key, int value) {
if (keyToNode.containsKey(key)) {
Node node = keyToNode.get(key);
node.val = value;
dll.update(node);
return;
}
if (keyToNode.size() == capacity) {
Node removeNode = dll.popleft();
keyToNode.remove(removeNode.key);
}
Node node = new Node(key, value);
keyToNode.put(key, node);
dll.append(node);
return;
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/
// time O(1)
// space O(capacity)
// using linked list and dll and hashmap
/*
1. maintain key_node hashmap
2. maintain dll
3. maintain capacity
4. if get() or put(), dll update the recent used node to the dll's tail or just append node to tail
5. if exceed capacity, dll popleft the least recent used node and pop it from hashmap
*/