链表 + HashMap
链表可以实现O(1)
删除某个节点,O(1)
插入元素到头部
import java.util.*; class KeyNode{ public int key; } class KeyVal{ public int val; public KeyNode keyNode; } class LruMap{ int maxSize; HashMap<Integer, KeyVal> keyValMap; // 链表 O(1) 实现删除 LinkedList<KeyNode> keyLinkList; public LruMap(int size) { keyValMap = new HashMap<>(); this.maxSize = size; keyLinkList = new LinkedList<>(); } public int get(int key){ if(keyValMap.containsKey(key)){ KeyVal keyVal = keyValMap.get(key); int val = keyVal.val; KeyNode oldKeyNode = keyVal.keyNode; KeyNode newKeyNode = new KeyNode(); newKeyNode.key = key; // 2。位置改变下 keyLinkList.remove(oldKeyNode); keyLinkList.addFirst(newKeyNode); // 1。改变元素值 keyVal.keyNode = newKeyNode; keyValMap.put(key, keyVal); return val; } return -1; } public void set(int key, int val){ if(keyValMap.isEmpty()){ KeyNode keyNode = new KeyNode(); keyNode.key = key; KeyVal keyVal = new KeyVal(); keyVal.val = val; keyVal.keyNode = keyNode; keyValMap.put(key, keyVal); keyLinkList.addFirst(keyNode); }else { if(keyValMap.containsKey(key)){ // 原来就存在 KeyVal keyVal = keyValMap.get(key); KeyNode oldKeyNode = keyVal.keyNode; KeyNode newKeyNode = new KeyNode(); newKeyNode.key = key; // 2。位置改变下 keyLinkList.remove(oldKeyNode); keyLinkList.addFirst(newKeyNode); // 1。改变元素值 keyVal.val = val; keyVal.keyNode = newKeyNode; keyValMap.put(key, keyVal); }else { // 新增的key // 需要判断是不是满了 if(keyValMap.size() == maxSize) { // 满了要删除链表尾部元素 KeyNode removeKey = keyLinkList.removeLast(); keyValMap.remove(removeKey.key); } // 添加元素,加到链表头部 KeyNode keyNode = new KeyNode(); keyNode.key = key; KeyVal keyVal = new KeyVal(); keyVal.val = val; keyVal.keyNode = keyNode; keyValMap.put(key, keyVal); keyLinkList.addFirst(keyNode); } } } } public class Main { public static Scanner sc = new Scanner(System.in); public static void main(String[] args) { int n = sc.nextInt(); int k = sc.nextInt(); LruMap lruMap = new LruMap(k); for (int i = 0; i < n; i++) { int op = sc.nextInt(); if(op == 1){ // set int key = sc.nextInt(); int val = sc.nextInt(); lruMap.set(key, val); } if(op == 2){ // get int key = sc.nextInt(); System.out.println(lruMap.get(key)); } } } } /* 6 3 1 1 1 1 2 2 1 3 2 2 1 1 4 4 2 2 1 -1 */