LeetCode——LRU Cache
2015-10-17 23:52
429 查看
Description:
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:
题目大意是让设计一个基于LRU的缓存,即最近最后用的保留。
实现LRU缓存有几种方法,链表+HashMap结构实现,LinkedHashMap的实现(继承、组合)、FIFO实现。
具体见我的博客:
这里使用LikedHashMap的组合实现,简单高效。
网上比较好的答案代码也有上百行,时间也是几百毫秒,这样看起来JDK中的LinkedHashMap的实现还是很高效的。
在不必要的情况下最好不要重复造轮子——大神
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:
getand
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的组合实现,简单高效。
public class LRUCache { private int capacity; private java.util.LinkedHashMap<Integer, Integer> cache = new java.util.LinkedHashMap<Integer, Integer>(capacity,0.75f,true) { @Override protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) { return size() > capacity; } }; public LRUCache(int capacity) { this.capacity = capacity; } public int get(int key) { Integer res = cache.get(key); return res==null?-1:res; } public void set(int key, int value) { cache.put(key, value); } }
网上比较好的答案代码也有上百行,时间也是几百毫秒,这样看起来JDK中的LinkedHashMap的实现还是很高效的。
在不必要的情况下最好不要重复造轮子——大神
相关文章推荐
- swift2.0 UIColor Use RGB
- Big ball of Mud
- [LeetCode]Candy
- ubantu15.04下安装配置docker
- Android基础学习之Socket、Http、Json网络编程
- python_9(获取字典值、函数参数、函数返回值、lambda的函数用法)
- QuickFix/N简介
- iOS开发技巧之code snippets(代码片段)
- K-Fold Cross Validation
- [POJ 1797]Heavy Transportation[SPFA]
- Git & Github 一页简明笔记(转)main
- IOS开发之----协议与委托(Protocol and Delegate) 实例解析
- LeetCode解题报告--Reverse Nodes in k-Group
- c 语言基础 printf的理解
- QuickFIX/N入门:(三)如何配置QuickFIX/N
- circlePageIndicator结合viewpager的一个例子
- Java中方法的重载与重写
- 【云计算虚拟化】虚拟化学习认识总结
- 黑马程序员——Java异常
- 用python3.x与mysql数据库构建简单的爬虫系统(转)