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

    Description:

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

    get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
    set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

    题目大意是让设计一个基于LRU的缓存,即最近最后用的保留。

    实现LRU缓存有几种方法,链表+HashMap结构实现,LinkedHashMap的实现(继承、组合)、FIFO实现。

    具体见我的博客:

    这里使用LikedHashMap的组合实现,简单高效。

     1 public class LRUCache {
     2     
     3     private int capacity;
     4     
     5     private java.util.LinkedHashMap<Integer, Integer> cache = new java.util.LinkedHashMap<Integer, Integer>(capacity,0.75f,true) {
     6         @Override
     7         protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
     8             return size() > capacity;
     9         }
    10     };
    11     
    12     public LRUCache(int capacity) {
    13         this.capacity = capacity;
    14     }
    15     
    16     public int get(int key) {
    17         Integer res = cache.get(key);
    18         return res==null?-1:res;
    19     }
    20     
    21     public void set(int key, int value) {
    22         cache.put(key, value);
    23     }
    24 }

    网上比较好的答案代码也有上百行,时间也是几百毫秒,这样看起来JDK中的LinkedHashMap的实现还是很高效的。

    在不必要的情况下最好不要重复造轮子——大神

  • 相关阅读:
    lr文件下载脚本(文件参数化重命名)
    测试部工作不受重视怎么办?
    质量管理浅谈
    测试人员职业规划
    十年软件测试经验总结
    如何管理测试项目?
    ES性能测试
    将.dat文件导入数据库
    NLPIR_Init文本分词-总是初始化失败,false,Init ICTCLAS failed!
    JavaScript-也来谈--闭包
  • 原文地址:https://www.cnblogs.com/wxisme/p/4888648.html
Copyright © 2011-2022 走看看