我正在尝试通过LeetCode(https://leetcode.com/problems/lru-cache/description/)解决此问题,但是我发现特定输入存在问题。我也在使用他们的论坛,但是他们花了很长时间才能回复。
我想知道为什么此条目的最终输出[“ LRUCache”,“ put”,“ put”,“ get”,“ put”,“ put”,“ get”] [[2],[2,1],[2,2],[2],[1,1],[4,1],[2]]是(-1)而不是2。
据我所知,缓存的最终配置为[(4,1),(2,2)),然后返回2,而不是-1。
谢谢!
这是我写的代码:
public class LRUCache {
HashMap<Integer, Integer> keyToArrayPosition = new HashMap<>();
Tuple [] cache;
int head;
int tail;
int capacity;
public LRUCache(int capacity) {
this.capacity = capacity;
cache = new Tuple[this.capacity];
head = 0;
tail = 0;
}
public int get(int key)
{
if(keyToArrayPosition.keySet().contains(key))
{
int position = keyToArrayPosition.get(key);
Tuple t = cache[position];
return t.value;
}
return -1;
}
public void put(int key, int value)
{
Tuple t = new Tuple(key, value);
//set
if(keyToArrayPosition.keySet().contains(key))
{
int position = keyToArrayPosition.get(key);
cache[position] = t;
return;
}
if(tail <= capacity - 1)
{
cache[tail] = t;
keyToArrayPosition.put(key, tail);
tail++;
}
else
{
tail--;
keyToArrayPosition.remove(cache[cache.length - 1].key);
for(int i = tail; i > 0; i--)
{
cache[i] = cache[i - 1];
keyToArrayPosition.put(cache[i].key, i);
}
cache[0] = t;
keyToArrayPosition.put(key, 0);
tail++;
}
}
}
class Tuple
{
public int key;
public int value;
public Tuple(int key, int value)
{
this.key = key;
this.value = value;
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/