https://www.nowcoder.com/practice/5dfded165916435d9defb053c63f1e84?tpId=295&tqId=2427094&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj
public class Solution { Map<Integer,Integer> map; int capacity; public Solution(int capacity) { // write code here this.capacity = capacity; // LinkedHashMap可以保证插入有序 map = new LinkedHashMap<>(capacity); } public int get(int key) { // write code here Integer value = map.get(key); if(value!=null){ if(map.size()>1){ map.remove(key); map.put(key,value); // 存入最后 } }else{ return -1; } return value; } public void set(int key, int value) { // write code here if(map.containsKey(key)){ map.remove(key); } if(map.size()>=capacity){ //这中相当于有一个指针,指向第一个数的前面 keySet() 返回key的集合 //next() 取出下一个数,指针指向下一位 Integer firstKey = map.keySet().iterator().next(); map.remove(firstKey); } map.put(key,value); } }