力扣labuladong一刷day53天LFU 算法

2024-01-08 13:53:02

力扣labuladong一刷day53天LFU 算法

一、460. LFU 缓存

题目链接: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);
 */

文章来源:https://blog.csdn.net/qq_43511039/article/details/135406317
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。