2021.10.06 - 115.设计LRU缓存结构
作者:互联网
文章目录
1. 题目
2. 思路
(1) HashMap+队列
- 利用HashMap存储键值对数据,利用队列控制数据的更替。
3. 代码
import java.util.*;
public class Test {
public static void main(String[] args) {
}
}
class Solution {
public int[] LRU(int[][] operators, int k) {
Map<Integer, Integer> map = new HashMap<>();
Queue<Integer> queue = new LinkedList<>();
int[] res = new int[operators.length];
int index = 0;
for (int i = 0; i < operators.length; i++) {
switch (operators[i][0]) {
case 1:
map.put(operators[i][1], operators[i][2]);
queue.offer(operators[i][1]);
if (queue.size() > k) {
map.remove(queue.poll());
}
break;
case 2:
if (map.containsKey(operators[i][1])) {
res[index++] = map.get(operators[i][1]);
queue.remove(operators[i][1]);
queue.offer(operators[i][1]);
} else {
res[index++] = -1;
}
break;
}
}
return Arrays.copyOfRange(res, 0, index);
}
}
标签:queue,06,2021.10,map,int,index,operators,115,HashMap 来源: https://blog.csdn.net/qq_44021223/article/details/120623860