-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path146.java
73 lines (70 loc) · 1.78 KB
/
146.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
class LRUCache {
class ListNode {
int val;
int key;
ListNode pre;
ListNode next;
ListNode(){}
ListNode(int k,int v){
val = v;
key = k;
}
}
Map<Integer,ListNode> map;
int cap;
int CAPACITY;
ListNode head;
ListNode tail;
public LRUCache(int capacity) {
cap = 0;
CAPACITY = capacity;
map = new HashMap<>();
head = new ListNode();
head.pre = null;
tail = new ListNode();
tail.next = null;
head.next = tail;
tail.pre = head;
}
public int get(int key) {
ListNode node = map.get(key);
if(node==null) return -1;
else moveToHead(node);
return node.val;
}
public void put(int key, int value) {
ListNode node = map.get(key);
if(node==null){
ListNode newNode = new ListNode(key,value);
map.put(key,newNode);
newNode.pre = head;
newNode.next = head.next;
head.next.pre = newNode;
head.next = newNode;
++cap;
if(cap>CAPACITY){
map.remove(tail.pre.key);
tail.pre = tail.pre.pre;
tail.pre.next = tail;
--cap;
}
}else{
node.val = value;
moveToHead(node);
}
}
private void moveToHead(ListNode node){
node.pre.next = node.next;
node.next.pre = node.pre;
node.pre = head;
node.next = head.next;
head.next.pre = node;
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);
*/