|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.LinkedHashSet; |
| 5 | + |
| 6 | +public class _460 { |
| 7 | + /** |
| 8 | + * Wikipedia: The simplest method to employ an LFU algorithm is to assign a counter to every |
| 9 | + * block that is loaded into the cache. Each time a reference is made to that block the counter |
| 10 | + * is increased by one. When the cache reaches capacity and has a new block waiting to be |
| 11 | + * inserted the system will search for the block with the lowest counter and remove it from the |
| 12 | + * cache. |
| 13 | + * |
| 14 | + * Policy to handle frequency ties: based on timestamp, the entries that get set into cache earlier will be evicted first. |
| 15 | + */ |
| 16 | + |
| 17 | + class LFUCache { |
| 18 | + /**credit: https://discuss.leetcode.com/topic/69737/java-o-1-very-easy-solution-using-3-hashmaps-and-linkedhashset/2*/ |
| 19 | + HashMap<Integer, Integer> vals; |
| 20 | + HashMap<Integer, Integer> counts; |
| 21 | + HashMap<Integer, LinkedHashSet<Integer>> lists; |
| 22 | + int cap; |
| 23 | + int min = -1; |
| 24 | + public LFUCache(int capacity) { |
| 25 | + cap = capacity; |
| 26 | + vals = new HashMap<>(); |
| 27 | + counts = new HashMap<>(); |
| 28 | + lists = new HashMap<>(); |
| 29 | + lists.put(1, new LinkedHashSet<>()); |
| 30 | + } |
| 31 | + |
| 32 | + public int get(int key) { |
| 33 | + if(!vals.containsKey(key)) |
| 34 | + return -1; |
| 35 | + int count = counts.get(key); |
| 36 | + counts.put(key, count+1); |
| 37 | + lists.get(count).remove(key); |
| 38 | + if(count==min && lists.get(count).size()==0) |
| 39 | + min++; |
| 40 | + if(!lists.containsKey(count+1)) |
| 41 | + lists.put(count+1, new LinkedHashSet<>()); |
| 42 | + lists.get(count+1).add(key); |
| 43 | + return vals.get(key); |
| 44 | + } |
| 45 | + |
| 46 | + public void put(int key, int value) { |
| 47 | + if(cap<=0) |
| 48 | + return; |
| 49 | + if(vals.containsKey(key)) { |
| 50 | + vals.put(key, value); |
| 51 | + get(key); |
| 52 | + return; |
| 53 | + } |
| 54 | + if(vals.size() >= cap) { |
| 55 | + int evit = lists.get(min).iterator().next(); |
| 56 | + lists.get(min).remove(evit); |
| 57 | + vals.remove(evit); |
| 58 | + } |
| 59 | + vals.put(key, value); |
| 60 | + counts.put(key, 1); |
| 61 | + min = 1; |
| 62 | + lists.get(1).add(key); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | +} |
0 commit comments