题目
import java.util.*;
public class Solution {
public static void main(String[] args) {
int[][] arr = new int[][]{{1,1,1},{1,2,2},{1,3,2},{2,1},{1,4,4},{2,2}};
int[] lruArr = LRU(arr, 3);
System.out.println(Arrays.toString(lruArr));
System.out.println("---------------------");
int[][] arr1 = new int[][]{{1,1,1},{1,2,2},{2,1},{1,3,3},{2,2},{1,4,4},{2,1},{2,3},{2,4}};
int[] lruArr1 = LRU(arr1, 2);
System.out.println(Arrays.toString(lruArr1));
}
public static int[] LRU (int[][] operators, int k){
List<Integer> temp = new ArrayList<>();
Map<Integer, Integer> cache = new LinkedHashMap<>();//要更新热度,删除,增加,所以用LinkedHashMap(哈希表+双向链表)
for(int[] op : operators) {
if (op[0] == 1) { //opt==1
cache.put(op[1], op[2]);
//超出阈值k要更新缓存
if (cache.size() > k) {
cache.remove(cache.keySet().iterator().next());
}
} else {
//opt==2
Integer value = cache.get(op[1]);
if (value != null) {
//更新热度
cache.remove(op[1]);//删除第一个key,从左往右
cache.put(op[1], value);//排在最后面最新,热度最高
temp.add(value);//结果
} else {
temp.add(-1);
}
}
}
//转成数组
int[] result = new int[temp.size()];
for(int i=0;i<temp.size();i++) {
result[i]=temp.get(i);
}
return result;
}
}
输出
主要是int[] LRU (int[][] operators, int k)
方法,测试通过
LeetCode版本
// 手动双链表 + HashMap,不取巧用LinkedHashMap
class LRUCache {
int capacity;
int size;
Node head;
Map<Integer, Node> map = new HashMap<>();
static class Node {
int key;
int val;
Node next;
Node prev;
Node () {}
Node(int key, int val) {
this.key = key;
this.val = val;
}
Node remove() {
prev.next = next;
next.prev = prev;
next = null;
prev = null;
return this;
}
void insert(Node node) {
node.next = next;
node.prev = this;
next.prev = node;
next = node;
}
}
public LRUCache(int capacity) {
this.capacity = capacity;
head = new Node();
head.next = head;
head.prev = head;
}
public int get(int key) {
Node node = map.get(key);
if (node == null) return -1;
node = node.remove();
head.insert(node);
return node.val;
}
public void put(int key, int value) {
Node node = map.get(key);
if (node == null) {
node = new Node(key, value);
map.put(key, node);
size++;
} else {
node = node.remove();
node.val = value;
}
head.insert(node);
if (size > capacity) {
Node removed = head.prev.remove();
map.remove(removed.key);
size--;
}
}
}