力扣labuladong——一刷day89

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • [一、力扣460. LFU 缓存](#一、力扣460. LFU 缓存)

前言


LFU 算法是要复杂很多的,而且经常出现在面试中,因为 LFU 缓存淘汰算法在工程实践中经常使用,也有可能是因为 LRU 算法太简单了。不过话说回来,这种著名的算法的套路都是固定的,关键是由于逻辑较复杂,不容易写出漂亮且没有 bug 的代码

一、力扣460. LFU 缓存

java 复制代码
class LFUCache {
    private int cap;
    private int minFreq;
    private HashMap<Integer,Integer> keyToVal;
    private HashMap<Integer,Integer> keyToFreq;
    private HashMap<Integer,LinkedHashSet<Integer>> freqToKeys;

    public LFUCache(int capacity) {
        this.cap = capacity;
        minFreq = 0;
        keyToVal = new HashMap<>();
        keyToFreq = new HashMap<>();
        freqToKeys = new HashMap<>();
    }
    
    public int get(int key) {
        if(!keyToVal.containsKey(key)){
            return -1;
        }
        increase(key);
        return keyToVal.get(key);
    }
    
    public void put(int key, int value) {
        if(cap <= 0)return;
        if(keyToVal.containsKey(key)){
            keyToVal.put(key,value);
            increase(key);
            return;
        }
        if(cap <= keyToVal.size()){
            removeMinFreq();
        }
        keyToVal.put(key,value);
        keyToFreq.put(key,1);
        freqToKeys.putIfAbsent(1,new LinkedHashSet<Integer>());
        freqToKeys.get(1).add(key);
        this.minFreq = 1;
    }
    private void increase(int key){
        int freq = keyToFreq.get(key);
        keyToFreq.put(key,freq+1);
        freqToKeys.get(freq).remove(key);
        freqToKeys.putIfAbsent(freq+1,new LinkedHashSet<Integer>());
        freqToKeys.get(freq+1).add(key);
        if(freqToKeys.get(freq).isEmpty()){
            freqToKeys.remove(freq);
            if(freq == minFreq){
                this.minFreq ++;
            }
        }
    }
    private void removeMinFreq(){
        LinkedHashSet<Integer> list = freqToKeys.get(this.minFreq);
        int key = list.iterator().next();
        list.remove(key);
        if(list.isEmpty()){
            freqToKeys.remove(this.minFreq);
        }
        keyToFreq.remove(key);
        keyToVal.remove(key);
    }
}

/**
 * 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);
 */
相关推荐
wno70410 小时前
Spring Security权限控制
java·python·spring
杨运交11 小时前
[071][验证码模块]基于Spring拦截器的验证码认证设计思想
java·后端·spring
Geek-Chow11 小时前
CountDownLatch in Java
java
漂流瓶jz11 小时前
UVA-1442 洞穴 题解答案代码 算法竞赛入门经典第二版
c++·算法·题解·aoapc·算法竞赛入门经典·uva
圣保罗的大教堂11 小时前
leetcode 835. 图像重叠 中等
leetcode
SL_staff12 小时前
从RBAC到场景化授权:《无忧·企业文档》三级权限模型的技术实践解析
java·开源·产品
传奇开心果编程12 小时前
【springboot基础语法学与练】第 1 课:从零开始
java·spring boot·后端·学习
SL_staff12 小时前
财务系统慎用低代码?从数据模型闭环看合规落地的技术实践
java·低代码·全栈
叠层归一研究院12 小时前
基于极限自指的叠层归一宇宙结构理论——无元外部封闭系统的内生区分模型
人工智能·经验分享·算法·agi
滕州市燕猫虎计算机科技工作室个体工商户12 小时前
IDEA:Command line is too long
java·ide·intellij-idea