题解 | #设计LRU缓存结构#
设计LRU缓存结构
http://www.nowcoder.com/practice/5dfded165916435d9defb053c63f1e84
import java.util.*;
public class Solution {
private LinkedHashMap<Integer, Integer> linkedHashMap;
private int capacity;
// 构造函数
public Solution(int capacity) {
// write code here
this.capacity = capacity;
linkedHashMap = new LinkedHashMap<>(capacity);
}
public int get(int key) {
// write code here
int value = linkedHashMap.getOrDefault(key, -1);
if (value != -1) {
linkedHashMap.remove(key, value);
linkedHashMap.put(key, value);
}
return value;
}
public void set(int key, int value) {
// write code here
// 判断是插入操作还是变更操作
int op = linkedHashMap.getOrDefault(key, -1);
// 更改操作
if (op != -1) {
linkedHashMap.put(key, value);
}
// 插入操作
else {
int sz = linkedHashMap.size();
// 判断当前容量是否已经达到了上限
if (sz == capacity) {
linkedHashMap.remove(linkedHashMap.keySet().toArray()[0]);
linkedHashMap.put(key, value);
}
else {
linkedHashMap.put(key, value);
}
}
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution solution = new Solution(capacity);
* int output = solution.get(key);
* solution.set(key,value);
*/