DESC:
请你为 最不经常使用(LFU)缓存算法设计并实现数据结构。
实现 LFUCache 类:
注意「项的使用次数」就是自插入该项以来对其调用 get 和 put 函数的次数之和。使用次数会在对应项被移除后置为 0 。
为了确定最不常使用的键,可以为缓存中的每个键维护一个 使用计数器 。使用计数最小的键是最久未使用的键。
当一个键首次插入到缓存中时,它的使用计数器被设置为 1 (由于 put 操作)。对缓存中的键执行 get 或 put 操作,使用计数器的值将会递增。
示例:
提示:
CODE:
JAVA:
class LFUCache { private int capacity, minFreq; private MapkeyMap; private Map > freqMap; public LFUCache(int capacity) { this.minFreq = 0; this.capacity = capacity; this.keyMap = new HashMap(); this.freqMap = new HashMap(); } public int get(int key) { if (capacity == 0) { return -1; } if (!keyMap.containsKey(key)) { return -1; } else { Node node = keyMap.get(key); LinkedList freqList = freqMap.get(node.freq); freqList.remove(node); if (freqList.size() == 0) { if (node.freq == this.minFreq) { this.minFreq += 1; } } node.freq += 1; keyMap.put(key, node); freqList = freqMap.getOrDefault(node.freq, new LinkedList<>()); freqList.offerFirst(node); freqMap.put(node.freq, freqList); return node.val; } } public void put(int key, int value) { if (capacity == 0) { return; } if (keyMap.containsKey(key)) { Node node = keyMap.get(key); LinkedList freqList = freqMap.get(node.freq); freqList.remove(node); if (freqList.isEmpty()) { if (node.freq == this.minFreq) { this.minFreq++; } } node.val = value; node.freq += 1; // keyMap.put(key, node); freqList = freqMap.getOrDefault(node.freq, new LinkedList ()); freqList.offerFirst(node); freqMap.put(node.freq, freqList); } else { if (keyMap.size() == capacity) { LinkedList list = freqMap.get(this.minFreq); Node node = list.pollLast(); keyMap.remove(node.key); if (list.size() == 0) { this.minFreq += 1; } } Node node = new Node(key, value, 1); keyMap.put(key, node); this.minFreq = 1; LinkedList list = freqMap.getOrDefault(node.freq, new LinkedList<>()); list.offerFirst(node); freqMap.put(node.freq, list); } } class Node { private int freq, key, val; public Node() {} public Node(int key, int val, int freq) { this.key = key; this.val = val; this.freq = freq; } } } / * Your LFUCache object will be instantiated and called as such: * LFUCache obj = new LFUCache(capacity); * int param_1 = obj.get(key); * obj.put(key,value); */
PYTHON:
NOTES:
(Java版)
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/223265.html原文链接:https://javaforall.net
