Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:get andset.
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.
[分析]
使用hashmap和linkedList 的结合, java的 jdk 7 中的linkedHashMap 即实现了此接口.
LinkedHashMap 版本, 因为leetcode不支持java7, 所以自带main函数.
package lc;
import java.util.LinkedHashMap;
import java.util.Map;
public class LRU {
public static void main(String[] args) {
LRU lru = new LRU(20);
lru.set(2, 1);
int x = lru.get(2);
System.out.println(x);
}
private final int capacity;
private LinkedHashMap<Integer, Integer> cache;
public LRU(final int capacity) {
this.capacity = capacity;
this.cache = new LinkedHashMap<Integer, Integer>(16, 0.75f, true){
@Override
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);
}
}naive 版本
public class LRUCache {
private int capacity;
private int count;
private Map<Integer, ListNode> map;
private ListNode head;
public LRUCache(int capacity) {
this.capacity = capacity;
count = 0;
map = new HashMap<Integer, ListNode>();
head = new ListNode(0,0);
head.next = head;
head.prev = head;
}
public int get(int key) {
int x = -1;
if(map.containsKey(key) ) {
ListNode n = map.get(key);
x = n.val;
n.prev.next = n.next;
n.next.prev = n.prev;
n.prev = head;
n.next = head.next;
head.next.prev = n;
head.next = n;
}
return x;
}
public void set(int key, int value) {
if(map.containsKey(key)) {
ListNode n = map.get(key);
n.val = value;
n.prev.next = n.next;
n.next.prev = n.prev;
n.prev = head;
n.next = head.next;
head.next.prev = n;
head.next = n;
} else if(count<capacity) {
count++;
ListNode n = new ListNode(key,value);
map.put(key, n);
n.prev = head;
n.next = head.next;
head.next.prev = n;
head.next = n;
} else {
ListNode n = new ListNode(key,value);
map.put(key, n);
n.prev = head;
n.next = head.next;
head.next.prev = n;
head.next = n;
map.remove( head.prev.key );
head.prev.prev.next = head;
head.prev = head.prev.prev;
}
}
}
class ListNode{
public int key;
public int val;
public ListNode next;
public ListNode prev;
public ListNode(int key, int val) {
this.key = key;
this.val = val;
next = null;
prev = null;
}
}
本文介绍了一种Least Recently Used (LRU) 缓存机制的实现方式,并提供了两种不同的Java实现示例:一种利用LinkedHashMap,另一种采用双向链表和哈希表组合的方式。
500

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



