题目:
设计LRU缓存结构,该结构在构造时确定大小,假设大小为K,并有如下两个功能
- set(key, value):将记录(key, value)插入该结构
- get(key):返回key对应的value值
[要求]
- set和get方法的时间复杂度为O(1)
- 某个key的set或get操作一旦发生,认为这个key的记录成了最常使用的。
- 当缓存的大小超过K时,移除最不经常使用的记录,即set或get最久远的。
若opt=1,接下来两个整数x, y,表示set(x, y)
若opt=2,接下来一个整数x,表示get(x),若x未出现过或已被移除,则返回-1
对于每个操作2,输出一个答案。输入:[[1,1,1],[1,2,2],[1,3,2],[2,1],[1,4,4],[2,2]],3
输出:[1,-1]
首先分析题目中要求实现的两个操作,get和set,这里可以直接使用HashMap进行实现,不过这里对缓存区(Map)的大小有限制,所以后面需要进行限制,分情况处理,有空间或者是执行更新操作时,直接set,空间不足时则需要先删除后set,删除则是根据LRU算法的最近最少使用进行确定。LRU算法的最近最少使用,可以设计一个辅助类,类包含key和time两个字段,time从0开始递增,每次操作key时更新time的值来模拟时间,将所有的操作信息放到list中,在进行删除的时候对list降序排序,取最后的一个的key,在list和map中进行删除即可。
完整代码如下:
class UseTimes{ //存储最近最少使用
int key;
int time;
}
public static int[] LRU (int[][] operators, int k) {
// write code here
int count = 0; //标记最近使用,越大越靠前
Map<Integer, Integer> map = new HashMap<>(); //存储key-value
List<UseTimes> useList = new ArrayList<>(); //存储最近最少使用
//operators的二维数组,每一个行表示的一个操作,通过操作的第一个值指明是put还是set
List<Integer> res = new ArrayList<>();
for(int i=0;i<operators.length;i++) {
int symbol = operators[i][0]; //查看是get操作还是set操作
if(symbol==1) { //put 三个元素 进行处理,更新useList
int size = map.size();
Integer nowInteger = map.get(operators[i][1]);
if(size<k||nowInteger!=null) { //有空闲或者已经有位置了,直接插入
map.put(operators[i][1], operators[i][2]);
boolean flag = false;
for(int j=0;j<useList.size();j++) {
UseTimes now = useList.get(j);
if(now.key==operators[i][1]) {
now.time = count++;
flag = true;
}
}
if(flag==false) {
UseTimes use = new UseTimes();
use.key = operators[i][1];
use.time = count++;
useList.add(use);
}
}else { //空间不够且没有位置,先删除后插入(一定是新元素)
//找到最近最少使用的元素,在map中删除后插入新元素,更新时间戳
Collections.sort(useList,new Comparator<UseTimes>() { //将list按照时间降序排序
public int compare(UseTimes o1, UseTimes o2) {
return o2.time-o1.time;
}
});
int leasttUse = useList.get(useList.size()-1).key;
map.remove(leasttUse);
useList.remove(useList.size()-1);
map.put(operators[i][1], operators[i][2]);
UseTimes use = new UseTimes();
use.key = operators[i][1];
use.time = count++;
useList.add(use);
}
}else if(symbol==2) { //get 两个元素 进行处理,拿到返回结果
Integer result = map.get(operators[i][1]);
if(result==null) {
res.add(-1);
}else {
res.add(result);
for(int j=0;j<useList.size();j++) {
UseTimes now = useList.get(j);
if(now.key==operators[i][1]) {
now.time = count++;
}
}
}
}
}
int[] ans = new int[res.size()];
for(int i=0;i<res.size();i++) {
ans[i] = res.get(i);
}
return ans;
}