LeetCode 460. LFU Cache

  • 题目:460. LFU Cache
    设计并实现最不经常使用(LFU)缓存的数据结构。它应该支持以下操作:get 和 put。

    get(key) - 如果键存在于缓存中,则获取键的值(总是正数),否则返回 -1。
    put(key, value) - 如果键不存在,请设置或插入值。当缓存达到其容量时,它应该在插入新项目之前,使最不经常使用的项目无效。在此问题中,当存在平局(即两个或更多个键具有相同使用频率)时,最近最少使用的键将被去除。

  • 进阶:
    你是否可以在 O(1) 时间复杂度内执行两项操作?

  • 示例:
    LFUCache cache = new LFUCache( 2 /* capacity (缓存容量) */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // 返回 1
cache.put(3, 3);    // 去除 key 2
cache.get(2);       // 返回 -1 (未找到key 2)
cache.get(3);       // 返回 3
cache.put(4, 4);    // 去除 key 1
cache.get(1);       // 返回 -1 (未找到 key 1)
cache.get(3);       // 返回 3
cache.get(4);       // 返回 4
  • Code
//460. LFU Cache
public class LFUCache {

    //保存key,value
    HashMap<Integer,Integer> vals;
    //保存key对应value的访问次数
    HashMap<Integer,Integer> counts;
    //保存相同访问次数的key的set集合
    HashMap<Integer,LinkedHashSet<Integer>> lists;
    int cap;
    //初始化数据出现的频次
    int min=-1;

    public LFUCache(int capacity) {
        cap=capacity;
        vals=new HashMap<>();
        counts=new HashMap<>();
        lists=new HashMap<>();
    }

    public int get(int key) {
        if(!vals.containsKey(key))
            return -1;


        int count=counts.get(key);
        counts.put(key,count+1);
        lists.get(count).remove(key);

        //判断min要不要加1
        if(count==min&&lists.get(count).size()==0){
            min++;
        }

        if(!lists.containsKey(count+1)){
            lists.put(count+1,new LinkedHashSet<>());
        }
        lists.get(count+1).add(key);
        return vals.get(key);
    }

    public void put(int key, int value) {
        if(cap<=0)
            return;

        if(vals.containsKey(key)){
            vals.put(key,value);
            get(key);
            return;
        }

        if(vals.size()>=cap){
            int minFreKey=lists.get(min).iterator().next();
            lists.get(min).remove(minFreKey);
            vals.remove(minFreKey);
            counts.remove(minFreKey);
        }

        vals.put(key,value);
        counts.put(key,1);
        min=1;
        if(!lists.containsKey(1)){
            lists.put(1,new LinkedHashSet<>());
        }
        lists.get(1).add(key);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值