# 如何设计实现一个LRU Cache？

### 1. 什么是LRU Cache？

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.

### 2.实现思路

public class LRUCache {
class Node {
Node pre;
Node next;
Integer key;
Integer val;
Node(Integer k, Integer v) {
key = k;
val = v;
}
}
Map<Integer, Node> map = new HashMap<Integer, Node>();
// The tail (youngest) of the doubly linked list.
Node tail;
int cap;
public LRUCache(int capacity) {
cap = capacity;
tail = new Node(null, null);
}
public int get(int key) {
Node n = map.get(key);
if(n!=null) {
n.pre.next = n.next;
n.next.pre = n.pre;
appendTail(n);
return n.val;
}
return -1;
}
public void set(int key, int value) {
Node n = map.get(key);
// existed
if(n!=null) {
n.val = value;
map.put(key, n);
n.pre.next = n.next;
n.next.pre = n.pre;
appendTail(n);
return;
}
// else {
if(map.size() == cap) {
map.remove(tmp.key);
}
n = new Node(key, value);
// youngest node append taill
appendTail(n);
map.put(key, n);
}
private void appendTail(Node n) {
n.next = tail;
n.pre = tail.pre;
tail.pre.next = n;
tail.pre = n;
}
}

public class LRUCache {
private int capacity;
private Map<Integer, Integer> cache;
public LRUCache(int capacity) {
this.capacity = capacity;
this.cache = new java.util.LinkedHashMap<Integer, Integer> (capacity, 0.75f, true) {
// 定义put后的移除规则，大于容量就删除eldest
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > capacity;
}
};
}
public int get(int key) {
if (cache.containsKey(key)) {
return cache.get(key);
} else
return -1;
}
public void set(int key, int value) {
cache.put(key, value);
}
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120