美文网首页
LeetCode-146- LRU 缓存机制

LeetCode-146- LRU 缓存机制

作者: 醉舞经阁半卷书 | 来源:发表于2022-01-22 17:58 被阅读0次

    LRU 缓存机制

    题目描述:运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制 。
    实现 LRUCache 类:

    • LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
    • int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
    • void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。

    进阶:你是否可以在 O(1) 时间复杂度内完成这两种操作?

    示例说明请见LeetCode官网。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/lru-cache/
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    解法一:LinkedHashMap

    因为允许使用已有的数据结构,LinkedHashMap就支持,所以直接继承LinkedHashMap即可,当然这是偷懒的做法,如果了解LinkedHashMap的实现的话,照着实现就可以了。

    import java.util.LinkedHashMap;
    import java.util.Map;
    
    public class LeetCode_146 {
        public static void main(String[] args) {
            // 测试用例
            LRUCache lRUCache = new LRUCache(2);
            lRUCache.put(1, 1); // 缓存是 {1=1}
            lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
            lRUCache.get(1);    // 返回 1
            lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
            lRUCache.get(2);    // 返回 -1 (未找到)
            lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
            lRUCache.get(1);    // 返回 -1 (未找到)
            lRUCache.get(3);    // 返回 3
            lRUCache.get(4);    // 返回 4
        }
    }
    
    class LRUCache extends LinkedHashMap<Integer, Integer> {
        private int capacity;
    
        public LRUCache(int capacity) {
            super(capacity, 0.75F, true);
            this.capacity = capacity;
        }
    
        public int get(int key) {
            return super.getOrDefault(key, -1);
        }
    
        public void put(int key, int value) {
            super.put(key, value);
        }
    
        /**
         * 移除最久未使用的数据的条件:当缓存容量达到上线
         *
         * @param eldest
         * @return
         */
        @Override
        protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
            return size() > capacity;
        }
    }
    

    【每日寄语】 也许奋斗了一辈子的屌丝也只是个屌丝,也许咸鱼翻身了不过是一个翻了面的咸鱼,但至少我们有做梦的自尊,而不是丢下一句‘努力无用’心安理得地生活下去。

    相关文章

      网友评论

          本文标题:LeetCode-146- LRU 缓存机制

          本文链接:https://www.haomeiwen.com/subject/xvzuhrtx.html