代码之家  ›  专栏  ›  技术社区  ›  Jas

关于LRU缓存的leetcode问题的冲突输入

  •  0
  • Jas  · 技术社区  · 6 年前

    https://leetcode.com/problems/lru-cache/description/ )但我发现了一个特定输入的问题。我也在使用他们的论坛,但是他们回复的时间太长了。

    我想知道为什么这个条目的最终输出[“LRUCache”,“put”,“put”,“get”,“put”,“put”,“get”]

    据我所知,缓存的最终配置是[(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);
     */
    
    0 回复  |  直到 6 年前