@@ -8,41 +8,69 @@ public class LFUCache {
88 // <Key, Counts>
99 HashMap <Integer , Integer > counts ;
1010 // <Counts, Key LinkedList>
11- HashMap <Integer , LinkedHashSet <Integer >> lists ;
11+ HashMap <Integer , LinkedHashSet <Integer >> order ;
1212 int capacity ;
1313 int min = 1 ;
1414
1515 public LFUCache (int capacity ) {
1616 this .capacity = capacity ;
1717 vals = new HashMap <>();
1818 counts = new HashMap <>();
19- lists = new HashMap <>();
20- lists .put (1 , new LinkedHashSet <>());
19+ order = new HashMap <>();
20+ order .put (1 , new LinkedHashSet <>());
2121 }
2222
2323 public int get (int key ) {
2424 if (!vals .containsKey (key )) return -1 ;
2525
2626 int oldCount = counts .get (key );
2727 counts .put (key , oldCount + 1 );
28- if (oldCount == min && lists .get (oldCount ).size () == 1 ) {
28+ order .get (oldCount ).remove (key );
29+ if (oldCount == min && order .get (oldCount ).size () == 0 ) {
2930 min = oldCount + 1 ;
3031 }
31- lists .get (oldCount + 1 ).add (key );
32+ if (!order .containsKey (oldCount + 1 )) {
33+ order .put (oldCount + 1 , new LinkedHashSet <>());
34+ }
35+ order .get (oldCount + 1 ).add (key );
3236
3337 return vals .get (key );
3438 }
3539
36- public void set (int key , int value ) {
40+ public void put (int key , int value ) {
41+ if (capacity == 0 ) return ;
3742 if (vals .containsKey (key ) || vals .size () < capacity ) {
3843 vals .put (key , value );
39- counts .put (key , counts .get (key ) + 1 );
40- lists .get (counts .get (key )).add (key );
44+ int oldCount = counts .getOrDefault (key , 0 );
45+ counts .put (key , oldCount + 1 );
46+
47+ if (!order .containsKey (oldCount + 1 )) {
48+ order .put (oldCount + 1 , new LinkedHashSet <>());
49+ }
50+ order .get (oldCount + 1 ).add (key );
51+ if (oldCount == 0 ) {
52+ min = 1 ;
53+ } else {
54+ order .get (oldCount ).remove (key );
55+ if (oldCount == min && order .get (oldCount ).size () == 0 ) {
56+ min = oldCount + 1 ;
57+ }
58+ }
4159 } else {
42- int removeKey = lists .get (min ).iterator ().next ();
60+ // evict
61+ int removeKey = order .get (min ).iterator ().next ();
4362 vals .remove (removeKey );
4463 counts .remove (removeKey );
45- lists .get (min ).remove (lists .get (min ).iterator ().next ());
64+ order .get (min ).remove (removeKey );
65+
66+
67+ min = 1 ;
68+ vals .put (key , value );
69+ counts .put (key , min );
70+ if (!order .containsKey (min )) {
71+ order .put (min , new LinkedHashSet <>());
72+ }
73+ order .get (min ).add (key );
4674 }
4775 }
4876}
0 commit comments