/*
* Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
* */
public class LRUCache
{
private Map<Integer, MapNode> map = null;
private int capacity;
private int size;
public LRUCache(int capacity)
{
this.capacity = capacity;
size = 0;
map = new LinkedHashMap<Integer,MapNode>();
}
public int get(int key)
{
if(map.containsKey(key) == false)
{
return -1;
}
else
{
int r = map.get(key).value;
//adjust the position of this item
MapNode tmMapNode = map.get(key);
map.remove(key);
map.put(key, tmMapNode);
return r;
}
}
public void set(int key, int value)
{
if(map.containsKey(key)==false)
{
if(size<capacity)
{
map.put(new Integer(key), new MapNode(key, value));
size++;
}
else
{
//if size capacity is zero , does this still work correctly?
//delete the first one which is the least used one
Iterator<Entry<Integer, MapNode>> iterator= map.entrySet().iterator();
Integer tmp = null;
if(iterator.hasNext())
{
tmp = iterator.next().getKey();
// map.remove(tmp);
// map.put(new Integer(key), new MapNode(key, value));
}
if(tmp != null)
{
map.remove(tmp);
map.put(new Integer(key), new MapNode(key, value));
}
}
}
else
{
//delete this node and change its content then add it,make it the last one
MapNode tmpMapNode = map.get(new Integer(key));
map.remove(new Integer(key));
tmpMapNode.value = value;
map.put(new Integer(key), tmpMapNode);
}
}
public class MapNode
{
int key;
int value;
public MapNode(int k, int v)
{
key = k;
value = v;
}
}
} 总结延伸://各种容器使用 map hashmap 等 他们操作的复杂度?,这里使用的LinkedHashMap其中数据保持插入顺序,后进的在头部
(notice that java.util.LinkedHashMap uses insertion-order.)
本文介绍了一种最少最近使用(LRU)缓存的数据结构设计与实现方法,通过使用LinkedHashMap来维持元素的访问顺序,实现了get和set两个核心操作。文中详细解释了当缓存满载时如何替换最久未使用的项。

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



