LRU 缓存实现某些测试用例的代码失败

问题描述

我正在一个网站上解决这个 LRU 缓存实现问题。我猜每个页面都有一个 Key , Value 组合。我的代码在一些隐藏的测试用例中失败了。谁能指出我代码中的任何逻辑错误

class LRUCache
{
    
   static LinkedHashMap<Integer,Integer>hm;
   static int cap;
    LRUCache(int cap)
    {
        // Intialize the cache capacity with the given
        // cap
        this.cap = cap;
        hm =   new LinkedHashMap<Integer,Integer>(cap);
    }

    // This method works in O(1)
    public static int get(int key)
    {
        // your code here
        if(hm.containsKey(key))
        return hm.get(key);
        return -1;
    }

    // This method works in O(1)
    public static void set(int key,int value)
    {
        if(hm.size()<cap){
            if(!hm.containsKey(key)){
                hm.put(key,value);
            }else{
                hm.remove(key);
                hm.put(key,value);
            }
        }else if (hm.size()==cap){
            if(!hm.containsKey(key))
            {
            int r =(int) hm.entrySet().iterator().next().getKey();
            hm.remove(r);
            hm.put(key,value);
            }
        }
        
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)