【哈希链表】LeetCode 146. LRU 缓存

题目链接

146. LRU 缓存

思路

使用Java中的 LinkedHashMap 类型,其数据结构示意图如下图所示。

image

因为该数据结构中最近添加的元素都在链表尾部,所以要让某个元素变为最近使用的状态,需要将它先删除,然后再插入。表头存储的就是最少使用的元素,使用 this.cache.keySet().iterator().next() 获得表头元素的 key

代码

class LRUCache{
    LinkedHashMap<Integer, Integer> cache;
    int capacity;

    public LRUCache(int capacity){

        this.cache = new LinkedHashMap<>(capacity);
        this.capacity = capacity;
    }

    public int get(int key){

        if(!this.cache.containsKey(key)){
            return -1;
        }

        makeRecent(key);
        return cache.get(key);
    }

    public void put(int key, int value){

        if(this.cache.containsKey(key)){
            makeRecent(key);
            this.cache.put(key, value);
            return;
        }

        if(this.cache.size() >= this.capacity){
            // the odestKey exists in the list head
            int oldestKey = this.cache.keySet().iterator().next();
            this.cache.remove(oldestKey);
        }

        this.cache.put(key, value);
    }

    private void makeRecent(int key){

        int val = this.cache.get(key);
        this.cache.remove(key);
        this.cache.put(key, val);
    }
}
posted @ 2023-01-06 09:38  Frodo1124  阅读(41)  评论(0编辑  收藏  举报