码迷,mamicode.com
首页 > 系统相关 > 详细

LeetCode——LRU Cache

时间:2015-10-18 01:06:12      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:

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结构实现,LikedHashMap的实现(继承、组合)、FIFO实现。

具体见我的博客:

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

 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的实现还是很高效的。

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

LeetCode——LRU Cache

标签:

原文地址:http://www.cnblogs.com/wxisme/p/4888648.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!