-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLFUCache.java
More file actions
66 lines (60 loc) · 1.67 KB
/
Copy pathLFUCache.java
File metadata and controls
66 lines (60 loc) · 1.67 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
import java.util.*;
public class LFUCache
{
int capacity;
Map<Integer, Integer> frequency;
Map<Integer, Integer> times;
Map<Integer, Integer> lookUpTable;
PriorityQueue<Integer> queue;
int time = 0;
public LFUCache(int capacity)
{
this.capacity = capacity;
frequency = new HashMap<>();
lookUpTable = new HashMap<>();
times = new HashMap<>();
queue = new PriorityQueue<>(new Comparator<Integer>()
{
@Override
public int compare(Integer o1, Integer o2)
{
return frequency.get(o1) != frequency.get(o2) ? frequency.get(o1) - frequency.get(o2) :
times.get(o1) - times.get(o2);
}
});
}
public int get(int key)
{
if (!lookUpTable.containsKey(key) || capacity == 0)
{
return -1;
}
frequency.put(key, frequency.getOrDefault(key, 0) + 1);
times.put(key, time++);
queue.remove(key);
queue.add(key);
return lookUpTable.get(key);
}
public void put(int key, int value)
{
if (capacity == 0)
{
return;
}
if (lookUpTable.containsKey(key))
{
queue.remove(key);
}
if (queue.size() == capacity && !lookUpTable.containsKey(key))
{
int removed = queue.poll();
lookUpTable.remove(removed);
frequency.remove(removed);
times.remove(removed);
}
lookUpTable.put(key, value);
frequency.put(key, frequency.getOrDefault(key, 0) + 1);
times.put(key, time++);
queue.add(key);
}
}