牛客题霸NC93题解
设计LRU缓存结构
https://www.nowcoder.com/practice/e3769a5f49894d49b871c09cadd13a61?tpId=117&&tqId=35015&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking
设计LRU缓存结构
难度:Medium
题目描述
设计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]
说明
第一次操作后:最常使用的记录为("1", 1) 第二次操作后:最常使用的记录为("2", 2),("1", 1)变为最不常用的 第三次操作后:最常使用的记录为("3", 2),("1", 1)还是最不常用的 第四次操作后:最常用的记录为("1", 1),("2", 2)变为最不常用的 第五次操作后:大小超过了3,所以移除此时最不常使用的记录("2", 2),加入记录("4", 4),并且为最常使用的记录,然后("3", 2)变为最不常使用的记录
备注:
1≤K≤N≤105 -2 \times 10^9 \leq x,y \leq 2 \times 10^9−2×109≤x,y≤2×109
题目答案
Java实现LRUCache可以通过继承LinkedHashMap来实现,要注意两点:
- 覆盖removeEldestEntry方法,指定Cache的存储大小
- super调用LinkedHashMap的构造器设置accessOrder字段为true(默认fasle,代表按插入顺序排序)
import java.util.*; public class Solution { /** * lru design * @param operators int整型二维数组 the ops * @param k int整型 the k * @return int整型一维数组 */ public int[] LRU (int[][] operators, int k) { // write code here if(operators == null){ return new int[0]; } LRUCache<Integer, Integer> lruCache = new LRUCache<>(k); List<Integer> list = new ArrayList<>(); for(int[] oper : operators){ if(oper[0] == 1){ lruCache.put(oper[1], oper[2]); } else{ int m = lruCache.getOrDefault(oper[1], -1); list.add(m); } } int[] res = new int[list.size()]; for(int i = 0; i < list.size(); i++){ res[i] = list.get(i); } return res; } } class LRUCache<K, V> extends LinkedHashMap<K, V>{ int capacity; public LRUCache(int capacity){ super(capacity*2, 0.75f, true); this.capacity = capacity; } @Override protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { return this.size() > capacity; } }