Question:
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.
Solution:
我的做法是map+list但是很慢~
public class LRUCache {
private int capacity;
private Map<Integer,Integer> map=new HashMap<Integer,Integer>();
private List<Integer> arr=new ArrayList<Integer>();
public LRUCache(int capacity) {
this.capacity=capacity;
}
public int get(int key) {
if(map.containsKey(key))
{
arr.remove((Integer)key);
arr.add(key);
return map.get(key);
}
return -1;
}
public void set(int key, int value) {
if(map.containsKey(key))
{
arr.remove((Integer)key);
arr.add(key);
map.put(key, value);
}
else
{
if(map.size()>capacity-1)
{
map.remove(arr.get(0));
arr.remove(0);
}
map.put(key,value);
arr.add(key);
}
}
}
明天起来看double linked list!
构造函数那里,因为一个错搞了半天!!!
public class LRUCache {
class DLinkedNode
{
int key;
int value;
DLinkedNode pre;
DLinkedNode post;
}
private void addAfterHead(DLinkedNode node)
{
node.pre=head;
node.post=head.post;
head.post.pre=node;
head.post=node;
}
private void remove(DLinkedNode node)
{
DLinkedNode pre=node.pre;
DLinkedNode post=node.post;
pre.post=post;
post.pre=pre;
}
private void moveToHead(DLinkedNode node)
{
this.remove(node);
this.addAfterHead(node);
}
private DLinkedNode popTail()
{
DLinkedNode current=tail.pre;
this.remove(current);
return current;
}
private int capacity;
private int count;
private Map<Integer,DLinkedNode> map=new HashMap<Integer,DLinkedNode>();
private DLinkedNode head;
private DLinkedNode tail;
public LRUCache(int capacity) {
this.capacity=capacity;
this.count=0;
head=new DLinkedNode();
head.pre=null;
tail=new DLinkedNode();
tail.post=null;
head.post=tail;
tail.pre=head;
}
public int get(int key) {
DLinkedNode cur = map.get(key);
if(cur==null)
return -1;
if(count!=1)
this.moveToHead(cur);
return cur.value;
}
public void set(int key, int value) {
DLinkedNode cur=map.get(key);
if(cur==null)
{
DLinkedNode newNode=new DLinkedNode();
newNode.key=key;
newNode.value=value;
this.map.put(key,newNode);
this.addAfterHead(newNode);
++count;
if(count>capacity)
{
DLinkedNode t=this.popTail();
this.map.remove(t.key);
--count;
}
}
else
{
cur.value=value;
this.moveToHead(cur);
}
}
}