-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path146.java
More file actions
67 lines (64 loc) · 1.58 KB
/
146.java
File metadata and controls
67 lines (64 loc) · 1.58 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
class LRUCache {
int capacity;
class Node{
int key,value;
Node next,prev;
Node(int k, int v) {
key = k;
value = v;
}
}
HashMap<Integer,Node> map;
Node head,tail;
public LRUCache(int capacity) {
this.capacity=capacity;
map=new HashMap<>(capacity);
head=new Node(0,0);
tail=new Node(0,0);
head.next=tail;
tail.prev=head;
}
public int get(int key) {
if(!map.containsKey(key)){
return -1;
}
Node node=map.get(key);
remove(node);
insertAtHead(node);
return node.value;
}
public void put(int key, int value) {
if(map.containsKey(key)){
Node node=map.get(key);
remove(node);
node.value=value;
insertAtHead(node);
}
else{
if(map.size()==capacity){
Node lru=tail.prev;
remove(lru);
map.remove(lru.key);
}
Node node = new Node(key, value);
insertAtHead(node);
map.put(key,node);
}
}
public void remove(Node node){
node.prev.next=node.next;
node.next.prev=node.prev;
}
public void insertAtHead(Node node){
head.next.prev=node;
node.next=head.next;
head.next=node;
node.prev=head;
}
}
/**
* 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);
*/