|
| 1 | +classLFUCache { |
| 2 | +privatestaticclassEntry { |
| 3 | +intkey; |
| 4 | +intvalue; |
| 5 | +intfreq; |
| 6 | + |
| 7 | +publicEntry(intkey,intvalue,intfreq) { |
| 8 | +this.key =key; |
| 9 | +this.value =value; |
| 10 | +this.freq =freq; |
| 11 | + } |
| 12 | + } |
| 13 | + |
| 14 | +privatefinalintcapacity; |
| 15 | +privateintminFreq =0; |
| 16 | +privatefinalMap<Integer,Entry>entries =newHashMap<>(); |
| 17 | +privatefinalMap<Integer,LinkedHashSet<Entry>>freqMap =newHashMap<>(); |
| 18 | + |
| 19 | +publicLFUCache(intcapacity) { |
| 20 | +this.capacity =capacity; |
| 21 | + } |
| 22 | + |
| 23 | +publicintget(intkey) { |
| 24 | +Entrye =entries.get(key); |
| 25 | +if (e ==null)return -1; |
| 26 | +updateFrequency(e); |
| 27 | +returne.value; |
| 28 | + } |
| 29 | + |
| 30 | +publicvoidput(intkey,intvalue) { |
| 31 | +if (capacity ==0)return; |
| 32 | +if (entries.containsKey(key)) { |
| 33 | +Entrye =entries.get(key); |
| 34 | +e.value =value; |
| 35 | +updateFrequency(e); |
| 36 | + }else { |
| 37 | +if (entries.size() ==capacity) { |
| 38 | +evictLeastFrequent(); |
| 39 | + } |
| 40 | +Entrye =newEntry(key,value,1); |
| 41 | +entries.put(key,e); |
| 42 | +freqMap.computeIfAbsent(1,k ->newLinkedHashSet<>()).add(e); |
| 43 | +minFreq =1;// Reset min frequency to 1 for new entry |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | +privatevoidupdateFrequency(Entrye) { |
| 48 | +intoldFreq =e.freq; |
| 49 | +intnewFreq =oldFreq +1; |
| 50 | + |
| 51 | +freqMap.get(oldFreq).remove(e); |
| 52 | +if (freqMap.get(oldFreq).isEmpty()) { |
| 53 | +freqMap.remove(oldFreq); |
| 54 | +if (minFreq ==oldFreq)minFreq++; |
| 55 | + } |
| 56 | + |
| 57 | +e.freq =newFreq; |
| 58 | +freqMap.computeIfAbsent(newFreq,k ->newLinkedHashSet<>()).add(e); |
| 59 | + } |
| 60 | + |
| 61 | +privatevoidevictLeastFrequent() { |
| 62 | +LinkedHashSet<Entry>minFreqEntries =freqMap.get(minFreq); |
| 63 | +EntrytoRemove =minFreqEntries.iterator().next(); |
| 64 | +minFreqEntries.remove(toRemove); |
| 65 | +if (minFreqEntries.isEmpty()) { |
| 66 | +freqMap.remove(minFreq); |
| 67 | + } |
| 68 | + |
| 69 | +entries.remove(toRemove.key); |
| 70 | + } |
| 71 | +} |