博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LRU Cache
阅读量:4073 次
发布时间:2019-05-25

本文共 1192 字,大约阅读时间需要 3 分钟。

LRU Cache

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.

Java代码:

public class LRUCache {   private java.util.LinkedHashMap
storage = new java.util.LinkedHashMap<>(); private int capacity; public LRUCache(int capacity) { this.capacity = capacity; } public int get(int key) { Integer value = storage.get(key); if(value == null){ return -1; } storage.remove(key); storage.put(key, value); return value; } public void set(int key, int value) { Integer val = storage.get(key); if (val == null && storage.size() == capacity) { storage.remove(storage.keySet().iterator().next()); } else if (val != null) { storage.remove(key); } storage.put(key, value); }}
 

转载地址:http://kvuni.baihongyu.com/

你可能感兴趣的文章
nginx+tomcat+memcached (msm)实现 session同步复制
查看>>
WAV文件解析
查看>>
WPF中PATH使用AI导出SVG的方法
查看>>
QT打开项目提示no valid settings file could be found
查看>>
android 代码实现圆角
查看>>
java LinkedList与ArrayList迭代器遍历和for遍历对比
查看>>
drat中构造方法
查看>>
JavaScript的一些基础-数据类型
查看>>
coursesa课程 Python 3 programming 统计文件有多少单词
查看>>
coursesa课程 Python 3 programming course_2_assessment_7 多参数函数练习题
查看>>
coursesa课程 Python 3 programming course_2_assessment_8 sorted练习题
查看>>
多线程使用随机函数需要注意的一点
查看>>
getpeername,getsockname
查看>>
所谓的进步和提升,就是完成认知升级
查看>>
如何用好碎片化时间,让思维更有效率?
查看>>
No.182 - LeetCode1325 - C指针的魅力
查看>>
Encoding Schemes
查看>>
带WiringPi库的交叉笔译如何处理二之软链接概念
查看>>
Java8 HashMap集合解析
查看>>
自定义 select 下拉框 多选插件
查看>>