LinkedHashMap实现 LRU

一、leetcode 题目

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

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

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

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

LRU 本身是一个操作系统的页面置换算法,least rencently used,也就是置换的时候置换掉那个最近使用的最少的,其实实现更加简化,使用一次就将它放到栈顶,移除的时候其实就是移除栈底的元素。

这个题目的重点在于要求 O(1) 时间复杂度,在对于 put 和 get 来说,O(1) 时间复杂度很容易想到 hashmap,但是对于 LRU 来说,需要元素有序,java 里提供了一个 linkedhashmap 类,源码的注释里就写了可以用来实现 cache。

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

    public LRUCache(int capacity) {
        this.capacity = capacity;
        cache = new LinkedHashMap<Integer, Integer>(capacity, 0.75f, true){
            @Override
            protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
                return cache.size() > capacity;
            }
        };
    }
    
    public int get(int key) {
        return cache.getOrDefault(key, -1);
    }
    
    public void put(int key, int value) {
        cache.put(key, 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);
 */

二、LinkedHashMap源码

基本思路就是 HashMap + 双向链表,在 Map 的基础上作出有序。放上一篇博客参考:

https://www.jianshu.com/p/8f4f58b4b8ab

posted @ 2020-11-17 11:27  Life_Goes_On  阅读(315)  评论(0编辑  收藏  举报