如何解决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 举报,一经查实,本站将立刻删除。