题解 | 设计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;
int index =0;
for (int i=0;i<list.size();i++) {
if (list.get(i).key == key) {
list.get(i).value=value;
index=i;
exist=true;
// Entry entry =null;
// entry =list.get(index);
// list.remove(index);
// list.add(entry);
break;
}
}
if(!exist){
list.add(new Entry(key,value));
if(list.size()>size){
list.remove(0);
}
}else{
Entry entry =null;
entry =list.get(index);
list.remove(index);
list.add(entry);
}
// Entry entry =null;
// entry =list.get(index);
// list.remove(index);
// list.add(entry);
}
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);
*/
有bug,不加get方法里的最后面的else对已经存在的节点刷新缓存居然也能通过;啧啧啧。



查看19道真题和解析