问题描述:
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.
原问题链接:https://leetcode.com/problems/lru-cache/
问题分析
这个问题的思路是希望能够设计一个类似于cache的数据结构,这个结构能够按照给定的大小构造。同时在进行get操作的时候能够查找到匹配的值,如果没有就返回-1。 set操作的时候则将将给定的值加入到里面,但是如果元素数量超过容量时,需要删除目前最不常用的元素。
如果从头开始设计这个结构的话会比较复杂,当然,这里有一个偷懒取巧的办法,就是利用java类库里现成的LinkedHashMap。它本身就已经支持这种访问了。
这是一种详细的实现代码:
import java.util.LinkedHashMap;
public class LRUCache {
private LinkedHashMap<Integer, Integer> map;
private final int CAPACITY;
public LRUCache(int capacity) {
CAPACITY = capacity;
map = new LinkedHashMap<Integer, Integer>(capacity, 1.0f, true){
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > CAPACITY;
}
};
}
public int get(int key) {
return map.getOrDefault(key, -1);
}
public void set(int key, int value) {
map.put(key, value);
}
}

本文介绍了一种基于Java的Least Recently Used (LRU) 缓存机制的设计与实现。该缓存支持get和set操作,并能根据最近最少使用的策略在达到容量限制时移除最旧条目。通过使用LinkedHashMap简化了实现过程。
584

被折叠的 条评论
为什么被折叠?



