题目链接:https://leetcode.cn/problems/lfu-cache/description/
class LFUCache {
HashMap<Integer, Integer> ktv;
HashMap<Integer, Integer> ktf;
HashMap<Integer, LinkedHashSet<Integer>> ftk;
int cap;
int minFreq;
public LFUCache(int capacity) {
ktv = new HashMap<>();
ktf = new HashMap<>();
ftk = new HashMap<>();
cap = capacity;
minFreq = 0;
}
public int get(int key) {
if (!ktv.containsKey(key)) {
return -1;
}
Integer v = ktv.get(key);
up(key);
return v;
}
private void up(int key) {
Integer f = ktf.get(key);
ftk.get(f).remove(key);
ftk.putIfAbsent(f+1, new LinkedHashSet<>());
ftk.get(f + 1).add(key);
ktf.put(key, f+1);
if (ftk.get(f).isEmpty()) {
ftk.remove(f);
if (minFreq == f) {
minFreq++;
}
}
}
public void put(int key, int value) {
if (ktv.containsKey(key)) {
ktv.put(key, value);
up(key);
return;
}
if (ktv.size() == cap) {
Integer next = ftk.get(minFreq).iterator().next();
ftk.get(minFreq).remove(next);
if (ftk.get(minFreq).isEmpty()) {
ftk.remove(minFreq);
}
ktv.remove(next);
ktf.remove(next);
}
ktv.put(key, value);
ktf.put(key, 1);
ftk.putIfAbsent(1, new LinkedHashSet<>());
ftk.get(1).add(key);
minFreq = 1;
}
}
/**
* Your LFUCache object will be instantiated and called as such:
* LFUCache obj = new LFUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/