LFU 缓存

问题描述

请你为 最不经常使用(LFU)缓存算法设计并实现数据结构。
实现 LFUCache 类:
• LFUCache(int capacity) - 用数据结构的容量 capacity 初始化对象
• int get(int key) - 如果键存在于缓存中,则获取键的值,否则返回 -1。
• void put(int key, int value) - 如果键已存在,则变更其值;如果键不存在,请插入键值对。当缓存达到其容量时,则应该在插入新项之前,使最不经常使用的项无效。在此问题中,当存在平局(即两个或更多个键具有相同使用频率)时,应该去除 最近最久未使用 的键。
注意「项的使用次数」就是自插入该项以来对其调用 get 和 put 函数的次数之和。使用次数会在对应项被移除后置为 0 。
为了确定最不常使用的键,可以为缓存中的每个键维护一个 使用计数器 。使用计数最小的键是最久未使用的键。
当一个键首次插入到缓存中时,它的使用计数器被设置为 1 (由于 put 操作)。对缓存中的键执行 get 或 put 操作,使用计数器的值将会递增。

解题方法

LinkedHashSet是Set集合的一个实现,具有set集合不重复的特点,同时具有可预测的迭代顺序,也就是我们插入的顺序

class LFUCache {
   //存放key 和 value 的键值对
    HashMap<Integer,Integer> keyToValue;
    //存放key 和 freq(出现频次) 的键值对
    HashMap<Integer,Integer> keyToFreq;
    //存放feq 和 keys(key的LinkedHashSet集合) 的键值对
    HashMap<Integer,LinkedHashSet<Integer>> freqToKeys;
    int minFreq;
    int capacity;
    public LFUCache(int capacity) {
       keyToValue = new HashMap<>();
       keyToFreq = new HashMap<>();
       this.capacity = capacity;
       this.minFreq = 0;   
        }
    
    public int get(int key) {
     if(!keyToValue.containsKey(key)) return -1;
     increaseFreq(key);
     return keyToValue.get(key);
    }
    
    public void put(int key, int value) {
      if(this.capacity <= 0) return;
      if(keyToValue.containsKey(key)){
         keyToValue.put(key, value);
         increaseFreq(key);
         return;
      }
      if(this.capacity <= keyToValue.size()){
          removeMinFreqKey();
      }
      keyToValue.put(key,value);
      keyToFreq.put(key, 1);
      freqToKeys.putIfAbsent(1, new LinkedHashSet<>());
      freqToKeys.get(1).add(key);
      this.minFreq = 1;
    }
    public void removeMinFreqKey(){
        LinkedHashSet<Integer> keyList = freqToKeys.get(this.minFreq);
        int deletedKey = keyList.iterator().next();
        keyList.remove(deletedKey);
        if(keyList.isEmpty()){
            freqToKeys.remove(this.minFreq);
        }
        keyToValue.remove(deletedKey);
        keyToFreq.remove(deletedKey);
    }
    public void increaseFreq(int key){
        int freq = keyToFreq.get(key);
        keyToFreq.put(key, freq +1);
        freqToKeys.get(freq).remove(key);
        freqToKeys.putIfAbsent(freq + 1, new LinkedHashSet<>());
        freqToKeys.get(freq + 1).add(key);
        if(freqToKeys.get(freq).isEmpty()){
            freqToKeys.remove(freq);
            if(freq == this.minFreq){
                this.minFreq++;
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值