-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache.java
More file actions
93 lines (76 loc) · 1.94 KB
/
LRUCache.java
File metadata and controls
93 lines (76 loc) · 1.94 KB
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
import java.util.HashMap;
import java.util.Map;
class LRUCache {
class Node{
Node pre, next;
int key, val;
Node(){}
Node(int key, int val){
this.key = key;
this.val = val;
}
}
private int size;
private int capacity;
private Map<Integer,Node> cache;
private Node head, tail;
public LRUCache(int capacity) {
this.size = 0;
this.capacity = capacity;
this.cache = new HashMap<>();
head = new Node();
tail = new Node();
head.next = tail;
tail.pre = head;
}
public int get(int key) {
if(cache.containsKey(key)){
Node node = cache.get(key);
moveToHead(node);
return node.val;
}
return -1;
}
public void put(int key, int value) {
Node node = cache.get(key);
if(node==null){
node = new Node(key,value);
cache.put(key, node);
addToHead(node);
size++;
if(size>capacity){
Node curTail = removeCurrentTail();
cache.remove(curTail.key);
size--;
}
}else{
node.val = value;
moveToHead(node);
}
}
private Node removeCurrentTail(){
Node curTail = tail.pre;
removeNode(curTail);
return curTail;
}
private void moveToHead(Node node){
removeNode(node);
addToHead(node);
}
private void removeNode(Node node){
node.pre.next = node.next;
node.next.pre = node.pre;
}
private void addToHead(Node node){
head.next.pre = node;
node.next = head.next;
node.pre = head;
head.next = node;
}
}
/**
* 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);
*/