代码实现一个LRU
设计思路
用一个map来存储 key-value 对;
用一个list来存储key的访问顺序,越后面的是越最近访问的。
C++
#include <vector>
#include <iostream>
#include <unordered_map>
using namespace std;
class LRUCache {
public:
LRUCache(int capacity) {
cap = capacity;
}
int get(int key) {
auto it = m.find(key);
if (it == m.end()) return -1;
// void splice ( iterator position, list<T,Allocator>& x, iterator it );
// 将it的值剪贴到要操作的x的position位置
keys.splice(keys.begin(), keys, it->second);
return it->second->second;
}
void put(int key, int value) {
auto it = m.find(key);
if (it != m.end()) keys.erase(it->second);
keys.push_front(make_pair(key, value));
m[key] = keys.begin();
if (m.size() > cap) {
int k = keys.rbegin()->first;
keys.pop_back();
m.erase(k);
}
}
private:
int cap;
list<pair<int, int>> keys;
unordered_map<int, list<pair<int, int>>::iterator> m;
};
int main() {
LRUCache cache(2);
cache.put(1, 1);
cache.put(2, 2);
cout << cache.get(1) << endl; // 1
cache.put(3, 3);
cout << cache.get(2) << endl; // -1
cache.put(4, 4);
cout << cache.get(1) << endl; // -1
cout << cache.get(3) << endl; // 3
cout << cache.get(4) << endl; // 4
return 0;
}
输出
1
-1
-1
3
4
Java
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class LRUCache {
private Map<Integer, Node> map;
private LinkedList<Node> orders;
private int capacity;
public LRUCache(int capacity) {
this.capacity = capacity;
map = new HashMap<>();
orders = new LinkedList<>();
}
public int get(int key) {
if (!map.containsKey(key)) return -1;
Node node = map.get(key);
orders.remove(node);
orders.addLast(node);
return node.value;
}
public void put(int key, int value) {
if (map.containsKey(key)) {
orders.remove(map.get(key));
map.remove(key);
}
Node node = new Node(key, value);
map.put(key, node);
orders.addLast(node);
if (map.size() > capacity) {
Node toDel = orders.removeFirst();
map.remove(toDel.key);
}
}
static class Node{
int key;
int value;
public Node(int key, int value) {
this.key = key;
this.value = value;
}
}
public static void main(String[] args) {
LRUCache lruCache = new LRUCache(2);
lruCache.put(1, 1);
lruCache.put(2, 2);
System.out.println(lruCache.get(1)); //1
lruCache.put(3, 3);
System.out.println(lruCache.get(2)); //-1
lruCache.put(4, 4);
System.out.println(lruCache.get(1)); //-1
System.out.println(lruCache.get(3)); //3
System.out.println(lruCache.get(4)); // 4
}
}
输出
1
-1
-1
3
4