(Java 已超时。。)就当复习下流操作吧
设计LRU缓存结构
http://www.nowcoder.com/questionTerminal/e3769a5f49894d49b871c09cadd13a61
注释都写在代码里了,比较清楚了。
用到的Java8 流操作比较多,不熟悉的可以看我写的博客,有一般用法的总结:
*博客: *https://blog.csdn.net/qq_36125181/article/details/108600930
import java.util.*;
import java.util.stream.Collectors;
public class Solution {
/**
* lru design
* @param operators int整型二维数组 the ops
* @param k int整型 the k
* @return int整型一维数组
*/
public static int[] LRU (int[][] operators, int k) {
// write code here
int length = operators.length;
List<Integer> res = new ArrayList<>(); // 返回的结果
List<Map<Integer,Integer>> list = new LinkedList<>(); // 维护数据的主要数据结构
for(int i = 0; i < length; ++i){
int key = operators[i][1];
if (operators[i][0] == 1) { //插入
int value = operators[i][2];
if (list.size() == k) { //覆盖或者替换
if (list.stream().anyMatch(item -> item.containsKey(key))) { //覆盖逻辑
list = list.stream().filter((Map map) -> map.get(key) == null).collect(Collectors.toList()); // 过滤掉键为key的map并重新生成list
}
else { //替换逻辑
list.remove(list.size()-1); //替换就直接删除最后一个
}
list.add(0 , new HashMap(){{put(key , value);}}); //添加新数据
}
else { //直接插入,当size != k 时也会有覆盖的情况
list = list.stream().filter((Map map) -> map.get(key) == null).collect(Collectors.toList()); // 过滤掉键为key的map并重新生成list
list.add(0 , new HashMap(){{put(key , value);}});
}
}
else { //查询(势必遍历list了.)
int size = res.size();
for (Map map : list) {
if (map.containsKey(key)) { //存在
res.add((Integer) map.get(key));
}
}
if (size == res.size()) res.add(-1); //没有找到目标,不用更新list
else { //需要更新list,逻辑和覆盖一样
list = list.stream().filter((Map map) -> map.get(key) == null).collect(Collectors.toList());
list.add(0 , new HashMap(){{put(key , res.get(res.size()-1));}});
}
}
}
return res.stream().mapToInt(Integer::valueOf).toArray();
}
}