LeetCode 460. LFU Cache

题目:

  • Design and implement a data structure for Least Frequently Used (LFU) cache. It should support the following operations: get and put.

  • get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.

  • put(key, value) - Set or insert the value if the key is not already present. When the cache reaches its capacity, it should invalidate the least frequently used item before inserting a new item. For the purpose of this problem, when there is a tie (i.e., two or more keys that have the same frequency), the least recently used key would be evicted.

  • Could you do both operations in O(1) time complexity?

LFUCache cache = new LFUCache( 2 /* capacity */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.get(3);       // returns 3.
cache.put(4, 4);    // evicts key 1.
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4

思路:

  • 变量

    • key——
    • value——
    • num——key被使用的次数,包括get和put(对已有key的put是更新,也要num++)
  • 容器

    • HashMap<Integer,int[]> valueHashMap——存储<key,int[value,num]>
    • TreeMap<Integer,LinkedHashSet<Integer>> numTreeMap——存储num,list<key>
  • numTreeMap为了确定容量不足时该删除谁,其中TreeMap能在O(1)时间复杂度保证最小frequency,LinkedHashSet能在O(1)时间复杂度remove开头key,remove任意key,add。

  • valueHashMap中存储的num是一份冗余信息,相当于索引,保证plusToTreeMap时,可以在O(1)的时间复杂度锁定位置。

代码:

public class LFUCache {
    private TreeMap<Integer,LinkedHashSet<Integer>> numTreeMap; // k:num,v:timeLinkedHashSet
    private HashMap<Integer,int[]> valueHashMap; // k:key,v:int[value,num]
    private int capacity;
    public LFUCache(int capacity) {
        this.capacity = capacity;
        numTreeMap = new TreeMap<>();
        valueHashMap = new HashMap<>();
    }

    //这些调试用的打印语句,一定要记得注释掉,毕竟打印时间复杂度是O(n)...
    public int get(int key) {
        // System.out.println(numTreeMap.toString());
        // System.out.println("~~~~~~~~~~~~~~~~~~~~get ("+key+")");
        if(!valueHashMap.containsKey(key)){
            // System.out.println("value: "+ -1);
            return -1;
        }
        int v = valueHashMap.get(key)[0];
        plusToTreeMap(key);
        // System.out.println("value: "+ v);
        return v;
    }

    public void put(int key, int value) {
        // System.out.println(numTreeMap.toString());
        // System.out.println("~~~~~~~~~~~~~~~~~~~~put ("+key+","+value+")");
        if(capacity==0){
            return;
        }
        if(valueHashMap.containsKey(key)){
            plusToTreeMap(key);
            valueHashMap.put(key,new int[]{value,valueHashMap.get(key)[1]});
        }else{
            if(valueHashMap.size()==capacity){
                // System.out.println("remove!");
                removeFromCache();
            }
            valueHashMap.put(key,new int[]{value,1});
            addToTreeMap(key);
        }
    }

    //新的key被put后,将valueHashMap中的num设成1,并在numTreeMap.get(1)中放入该key
    private void addToTreeMap(int key){
        LinkedHashSet<Integer> timeLinkedList;
        if(!numTreeMap.containsKey(1)){
            timeLinkedList = new LinkedHashSet<>();
            numTreeMap.put(1,timeLinkedList);
        }else{
            timeLinkedList = numTreeMap.get(1);
        }
        timeLinkedList.add(key);
    }

    //已有key被get或put后,要修改两个地方,一个是valueHashMap中的num++,一个是提升该key在numTreeMap中的位置。
    private void plusToTreeMap(int key){
        LinkedHashSet<Integer> timeLinkedList;
        int num = valueHashMap.get(key)[1]++;
        timeLinkedList = numTreeMap.get(num);
        timeLinkedList.remove(key);
        if(timeLinkedList.size()==0){
            numTreeMap.remove(num);
        }
        if(!numTreeMap.containsKey(num+1)){
            timeLinkedList = new LinkedHashSet<>();
            numTreeMap.put(num+1,timeLinkedList);
        }else{
            timeLinkedList = numTreeMap.get(num+1);
        }
        timeLinkedList.add(key);
    }

    // freshTreeMap函数的作用是将key提到当前次数的最后,开始时我以为put操作不影响frequently只影响recently,才写的这个,对本题来说没有作用。实际cache设计中我觉得使用该函数也许更合理
    // private void freshTreeMap(int key){
    //     LinkedHashSet<Integer> timeLinkedList;
    //     int num = valueHashMap.get(key)[1];
    //     timeLinkedList = numTreeMap.get(num);
    //     timeLinkedList.remove(key);
    //     timeLinkedList.add(key);
    // }

    //容器满了,又put了新的key,就需要调用removeFromCache,清理出一个空间。思路是先在numTreeMap找到最小frequently对应的时间队列timeLinkedList,再找到该队列的第一个元素,将它删除。如果此时timeLinkedList空了,要在numTreeMap中把该frequently的对应的timeLinkedList删除,保证以后numTreeMap.firstEntry().getValue()找到的timeLinkedList一定非空。
    private void removeFromCache(){
        LinkedHashSet<Integer> timeLinkedList = numTreeMap.firstEntry().getValue();
        int k = timeLinkedList.iterator().next();
        timeLinkedList.remove(k);
        valueHashMap.remove(k);
        if(timeLinkedList.size()==0){
            numTreeMap.remove(numTreeMap.firstEntry().getKey());
        }
    }
}

/**
 * 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);
 */
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值