力扣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);
 */
相关推荐
今天和Aboo结婚了吗1 小时前
【Broker一重启消息没了:一次RabbitMQ非持久化+没开Confirm的血亏事故】
java·rabbitmq·messagequeue·bug排查
daidaidaiyu6 小时前
一文学习 工作流开发 BPMN、 Flowable
java
2401_891482177 小时前
多平台UI框架C++开发
开发语言·c++·算法
SuniaWang7 小时前
《Spring AI + 大模型全栈实战》学习手册系列 · 专题六:《Vue3 前端开发实战:打造企业级 RAG 问答界面》
java·前端·人工智能·spring boot·后端·spring·架构
sheji34167 小时前
【开题答辩全过程】以 基于springboot的扶贫系统为例,包含答辩的问题和答案
java·spring boot·后端
88号技师8 小时前
2026年3月中科院一区SCI-贝塞尔曲线优化算法Bezier curve-based optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
t198751288 小时前
三维点云最小二乘拟合MATLAB程序
开发语言·算法·matlab
无敌昊哥战神8 小时前
【LeetCode 257】二叉树的所有路径(回溯法/深度优先遍历)- Python/C/C++详细题解
c语言·c++·python·leetcode·深度优先
㓗冽8 小时前
8皇后·改-进阶题16
数据结构
m0_726965988 小时前
面面面,面面(1)
java·开发语言