【LinkedHashMap】146. LRU cache

146. LRU cache

Problem-solving ideas

  • Unlike ordinary HashMap, LinkedHashMap will maintain the order of elements. This can provide a more predictable iteration order in some cases
  • Obtain the element directly because the element is used and put the element back at the end of the queue to indicate that the element was recently used.
  • To write an element, first if the element originally exists, you need to change the key to the most recently used element, delete the head element (the element that has not been used recently) and then write the element.
  • Change an element to the most recently used element: rewrite the element to the end of the queue

class LRUCache {
    
    
    int cap;
    // 与普通的 HashMap 不同,LinkedHashMap 会保持元素的有序性。这可以在某些情况下提供更可预测的迭代顺序
    LinkedHashMap<Integer,Integer> cache = new LinkedHashMap<>();

    public LRUCache(int capacity) {
    
    
        this.cap = capacity;// 初始化容器
    }
    
    public int get(int key) {
    
    
        if(!cache.containsKey(key)){
    
    
            return -1;
        }

        // 直接获取元素  因为使用到该元素 将该元素重新放入队尾 表示最近使用该元素
        makeRecently(key);
        return cache.get(key);
    }
    
    public void put(int key, int value) {
    
    
        if(cache.containsKey(key)){
    
    
            // 修改key的值
            cache.put(key,value);
            // 将key变为最近使用
            makeRecently(key);
            return;
        }

        // 删除对头元素 就是很久没用的
        if(cache.size() >= this.cap){
    
    
            // 链表头部就是最久未使用的key
            int oldestKey = cache.keySet().iterator().next();
            cache.remove(oldestKey);

        }

        cache.put(key,value);

    }

    // 计算最近使用的元素
    private void makeRecently(int key){
    
    
        int val = cache.get(key);// 获取元素

        // 移除key
        cache.remove(key);

        // 因为现在使用到该元素  所以将该元素插入队列尾部
        cache.put(key,val);
    }
}

/**
 * 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);
 */

おすすめ

転載: blog.csdn.net/qq_44653420/article/details/133219268