C++用unorder_map存Iterator,Java自己实现双向链表。目的都是为了实现快速删除LRUTable中的item。
C++版:
class LRUCache{
private:
list<pair<int, int>> LRUTable;
unordered_map<int, list<pair<int, int>>::iterator> cache;
int capacity;
public:
LRUCache(int capacity) {
this->capacity = capacity;
}
int get(int key) {
if(cache.find(key) != cache.end()) {
auto temp = cache[key];
LRUTable.erase(cache[key]);
LRUTable.push_front(*temp);
cache[key] = LRUTable.begin();
return temp->second;
}
else
return -1;
}
void set(int key, int value) {
if(cache.find(key) != cache.end()) {
cache[key]->second = value;
auto temp = cache[key];
LRUTable.erase(cache[key]);
LRUTable.push_front(*temp);
cache[key] = LRUTable.begin();
return;
}
if(cache.size() == this->capacity) {
cache.erase(LRUTable.back().first);
LRUTable.pop_back();
}
LRUTable.push_front(pair<int, int>(key, value));
cache[key] = LRUTable.begin();
return;
}
};
Java版:
public class LRUCache {
private HashMap<Integer, Node> cache = null;
private int capacity;
private Node head;
private Node tail;
public LRUCache(int capacity) {
this.capacity = capacity;
head = null;
tail = null;
cache = new HashMap<Integer, Node>();
}
public int get(int key) {
if(cache.containsKey(key)) {
Node current = cache.get(key);
moveNodeAhead(current);
return current.value;
}
return -1;
}
public void set(int key, int value) {
if(cache.containsKey(key)) {
Node current = cache.get(key);
moveNodeAhead(current);
current.value = value;
cache.put(key, current);
return;
}
if(cache.size() == this.capacity) {
Node last = tail;
tail = tail.pre;
if(tail != null)
tail.next = null;
cache.remove(last.key);
}
Node n = new Node(key, value);
insertNode(n);
cache.put(key, n);
}
private void moveNodeAhead(Node n) {
if(n == head)
return;
if(n == tail) {
tail = n.pre;
tail.next = null;
} else {
n.pre.next = n.next;
n.next.pre = n.pre;
}
n.pre = null;
n.next = head;
head.pre = n;
head = n;
}
private void insertNode(Node n) {
if(head == null && tail == null) {
head = n;
tail = n;
return;
}
n.next = head;
head.pre = n;
head = n;
}
}
class Node {
int key;
int value;
Node pre;
Node next;
Node(int k, int v) {
key = k;
value = v;
pre = null;
next = null;
}
}
由此可见,使用C++实现LRU Cache要比Java和Python简便的多。