LFU Cache
这个题吧…不看答案却是很难想到如何做到o(1)
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 |
class LFUCache { class Triple { int c; int k; int v; public Triple(int c, int k, int v) { this.c = c; this.k = k; this.v = v; } } Map<Integer, Triple> cache = new HashMap<>();// <key, Triple> Map<Integer, LinkedHashSet<Triple>> count = new HashMap<>(); //<count, <Triple>> int min = -1; int cap = 0; public LFUCache(int capacity) { this.cap = capacity; count.put(1, new LinkedHashSet<>()); } public int get(int key) { if(!cache.containsKey(key)) return -1; Triple t = cache.get(key); count.get(t.c).remove(t); if(t.c == min && count.get(min).isEmpty()){ count.remove(min); min++; } t.c++; count.putIfAbsent(t.c, new LinkedHashSet<Triple>()); count.get(t.c).add(t); return t.v; } public void put(int key, int value) { if(cap <= 0) return; if(cache.containsKey(key)) { Triple t = cache.get(key); t.v = value; get(key); return; } if (cache.size() == cap) { Iterator<Triple> it = count.get(min).iterator(); Triple t = it.next(); it.remove(); cache.remove(t.k); if(!it.hasNext()) { // if next is empty, clear the count count.remove(min); } } Triple tri = new Triple(key, value, 1); cache.put(key, tri); min = 1; // current is always with count 1 count.putIfAbsent(1, new LinkedHashSet<Triple>()); count.get(1).add(tri); } } /** * 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); */ |