zoukankan      html  css  js  c++  java
  • LeetCode——LRU Cache

    Q:设计和实现最近最少使用(LRU)缓存的数据结构。它应该支持以下操作:get和set。
    get(key)—如果键存在于缓存中,则获取键的值(总是正的),否则返回-1。
    put(key, value)——如果键不存在,则设置或插入该值。当缓存达到其容量时,它应该在插入新项之前使最近最少使用的项无效。
    你能在O(1)时间复杂度下做这两个操作吗?
    举例:

    LRUCache cache = new LRUCache( 2 /* capacity */ );
    
    cache.put(1, 1);
    cache.put(2, 2);
    cache.get(1);       // returns 1
    cache.put(3, 3);    // evicts key 2
    cache.get(2);       // returns -1 (not found)
    cache.put(4, 4);    // evicts key 1
    cache.get(1);       // returns -1 (not found)
    cache.get(3);       // returns 3
    cache.get(4);       // returns 4
    

    A:
    LRU算法:最近最少使用,简单来说就是将数据块中,每次使用过的数据放在数据块的最前端,然后将存在的时间最长的,也就是数据块的末端的数据剔除掉这就是LRU算法。
    1.使用LinkedHashMap。LinkedHashMap是有序的,且默认为插入顺序。

        public class LRUCache extends LinkedHashMap<Integer, Integer> {
            private int capacity;
    
            public LRUCache(int capacity) {
                super(capacity, 0.1f, true);//参数accessOrder就是用来指定是否按访问顺序,如果为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);
            }
    
            @Override
            protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
                return size() > capacity;
            }
        }
    

    2.哈希表+LinkedList
    轻松解决

    class LRUCache {
        private HashMap<Integer, Integer> map;
        private LinkedList<Integer> cache;
        private int cap;
    
        public LRUCache(int capacity) {
            this.cap = capacity;
            map = new HashMap<>();
            cache = new LinkedList<>();
        }
    
        public int get(int key) {
            if (map.containsKey(key)) {
                cache.remove((Integer) key);
                cache.addLast(key);
                return map.get(key);
            } else return -1;
        }
    
        public void put(int key, int value) {
            if (map.containsKey(key)) {
                cache.remove((Integer) key);
                cache.addLast(key);
                map.put(key, value);
            } else {
                if (cache.size() == cap) {
                    int first = cache.getFirst();
                    cache.removeFirst();
                    map.remove(first);
                }
                map.put(key, value);
                cache.addLast(key);
            }
        }
    }
    
  • 相关阅读:
    NPOI 菜鸟实践行之根据指定的模板生成Excel 2003格式的文件 (一)
    python循环字典
    对字典中找出最大的值
    通用解决方案:解决NHibernate SELECT 多表查询结果List绑定控件显示问题。
    读取Excel。。。
    哈,申请成功了。
    SharePoint 使用命令行备份过程中中断导致站点没有权限更改问题
    反射
    SharePoint 自定义主机标头与本地计算机名称不匹配,验证失败
    产生一个int数组,长度为100,并向其中随机插入1100,并且不能重复。自己写的算法
  • 原文地址:https://www.cnblogs.com/xym4869/p/12542297.html
Copyright © 2011-2022 走看看