题解 | 设计LRU缓存结构
设计LRU缓存结构
https://www.nowcoder.com/practice/5dfded165916435d9defb053c63f1e84
import java.util.*; public class Solution { Map<Integer, KeyOperate> lfuMap; LinkedList<KeyOperate> keyOperateList; int size; public Solution(int capacity) { // write code here lfuMap = new HashMap<>(capacity); keyOperateList = new LinkedList<>(); size = capacity; } public int get(int key) { if (lfuMap.containsKey(key)) { KeyOperate keyOperate = lfuMap.get(key); keyOperateList.remove(keyOperate); keyOperateList.addFirst(keyOperate); return keyOperate.getValue(); } return -1; } public void set(int key, int value) { if (lfuMap.containsKey(key)) { KeyOperate keyOperate = lfuMap.get(key); keyOperateList.remove(keyOperate); keyOperateList.addFirst(keyOperate); keyOperate.setValue(value); lfuMap.put(key, keyOperate); return; } KeyOperate keyOperate = new KeyOperate(key, value); if (lfuMap.size() == size) { KeyOperate last = keyOperateList.removeLast(); lfuMap.remove(last.getKey()); } lfuMap.put(key, keyOperate); keyOperateList.addFirst(keyOperate); } private class KeyOperate { private int key; private int value; public KeyOperate(int key,int value) { this.key = key; this.value = value; } public int getKey() { return key; } public void setKey(int key) { this.key = key; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } } } /** * Your Solution object will be instantiated and called as such: * Solution solution = new Solution(capacity); * int output = solution.get(key); * solution.set(key,value); */