-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLRUCache.java
78 lines (62 loc) · 1.66 KB
/
LRUCache.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
package com.smlnskgmail.jaman.leetcodejava.medium;
import java.util.HashMap;
import java.util.Map;
// https://leetcode.com/problems/lru-cache/
public class LRUCache {
private final Node head = new Node();
private final Node tail = new Node();
private final Map<Integer, Node> cache;
private final int capacity;
public LRUCache(int capacity) {
this.capacity = capacity;
cache = new HashMap<>(capacity);
head.next = tail;
tail.previous = head;
}
public int get(int key) {
Node node = cache.get(key);
if (node != null) {
remove(node);
add(node);
return node.val;
}
return -1;
}
public void put(int key, int value) {
Node node = cache.get(value);
if (node != null) {
remove(node);
node.val = value;
add(node);
} else {
if (cache.size() == capacity) {
cache.remove(tail.previous.key);
remove(tail.previous);
}
node = new Node();
node.key = key;
node.val = value;
cache.put(key, node);
add(node);
}
}
private void add(Node node) {
Node next = head.next;
head.next = node;
next.previous = node;
node.next = next;
node.previous = head;
}
private void remove(Node node) {
Node next = node.next;
Node previous = node.previous;
next.previous = previous;
previous.next = next;
}
private class Node {
int key;
int val;
Node previous;
Node next;
}
}