本文共 1680 字,大约阅读时间需要 5 分钟。
LRU
设计 LRU 缓存结构,该结构在构造时确定大小,假设大小为 K,并有如下两个功能
[要求]
若 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]
使用 Java 标准库 JDK 里的 LinkedHashMap
import java.util.*;public class Solution extends LinkedHashMap{ class LRUCache extends LinkedHashMap { private int capacity; public LRUCache(int capacity) { super(capacity, 0.75F,true); this.capacity = capacity; } public int get(int key) { return super.getOrDefault(key,-1); } public void put(int key, int value) { super.put(key,value); } @Override public boolean removeEldestEntry(Map.Entry eldest){ return size() > capacity; } } /** * lru design * @param operators int整型二维数组 the ops * @param k int整型 the k * @return int整型一维数组 */ public int[] LRU (int[][] operators, int k) { LRUCache lruCache = new LRUCache(k); int[] res = new int[(int) Arrays.stream(operators).filter(x -> x[0] == 2).count()]; for(int i = 0, j = 0; i < operators.length; i++) { if(operators[i][0] == 1) { lruCache.put(operators[i][1], operators[i][2]); } else { res[j++] = lruCache.get(operators[i][1]); } } return res; }}
转载地址:http://icjvb.baihongyu.com/