题解 | 设计LRU缓存结构
设计LRU缓存结构
https://www.nowcoder.com/practice/5dfded165916435d9defb053c63f1e84
import java.util.*;
public class Solution {
int size;
ArrayList<Entry> list = new ArrayList<Entry>();
public Solution(int capacity) {
// write code here
this.size = capacity;
}
public int get(int key) {
// write code here
int index=0;
Entry entry=null;
boolean exist=false;
for (int i=0;i<list.size();i++) {
if (list.get(i).key == key) {
index=i;
exist=true;
break;
}
}
if(exist){
entry=list.get(index);
list.remove(index);
list.add(entry);
return entry.value;
}
return -1;
}
public void set(int key, int value) {
// write code here
boolean exist=false;
for (Entry entry : list) {
if (entry.key == key) {
entry.value=value;
exist=true;
}
}
if(!exist){
list.add(new Entry(key,value));
if(list.size()>size){
list.remove(0);
}
}
}
static class Entry {
int key;
int value;
public Entry(int key, int value) {
this.key = key;
this.value = 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);
*/
用数组实现;数组的0号索引为最不经常使用的元素,每次访问完一个元素把该元素先从数组中删除再加入数组尾部;


查看23道真题和解析