-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path146.lru-缓存.java
More file actions
82 lines (72 loc) · 1.79 KB
/
146.lru-缓存.java
File metadata and controls
82 lines (72 loc) · 1.79 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
import java.util.HashMap;
import java.util.Map;
/*
* @lc app=leetcode.cn id=146 lang=java
*
* [146] LRU 缓存
*/
// @lc code=start
class LRUCache {
private final int capacity;
private final Node head = new Node();
private final Node tail = new Node();
private final Map<Integer, Node> cache = new HashMap<>();
protected static class Node {
int key;
int val;
Node next;
Node pre;
}
public LRUCache(int capacity) {
this.capacity = capacity;
head.next = tail;
tail.pre = head;
}
public int get(int key) {
Node n = cache.get(key);
if (n == null) {
return -1;
}
Node pre = n.pre;
Node next = n.next;
pre.next = next;
next.pre = pre;
n.pre = head;
n.next = head.next;
head.next = n;
n.next.pre = n;
return n.val;
}
public void put(int key, int value) {
Node n = cache.get(key);
if (n == null) {
n = new Node();
n.key = key;
n.val = value;
} else {
n.val = value;
Node pre = n.pre;
Node next = n.next;
pre.next = next;
next.pre = pre;
}
n.pre = head;
n.next = head.next;
head.next = n;
n.next.pre = n;
cache.put(key, n);
if (cache.size() > capacity) {
Node removalNode = tail.pre;
tail.pre = removalNode.pre;
removalNode.pre.next = tail;
cache.remove(removalNode.key);
}
}
}
/**
* 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);
*/
// @lc code=end