LFU Cache
Last updated
Last updated
Design and implement a data structure for cache. It should support the following operations: get
and put
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value)
- Set or insert the value if the key is not already present. When the cache reaches its capacity, it should invalidate the least frequently used item before inserting a new item. For the purpose of this problem, when there is a tie (i.e., two or more keys that have the same frequency), the least recently used key would be evicted.
Follow up: Could you do both operations in O(1) time complexity?
Example:
思路: 自定义 node class,双链表,class,双hashmap
node class:包括 key,value和这个node的freq, next, prev指针
双链表:支持 add,remove, remove last
用一个hashmap nodeMap建立 key和node的mapping,node是 map的value
用另一个hashmap freqMap 建立freq和node list的映射,freq是key, 具有同样freq的node list
LFU 更新策略
1.get(); nodeMap 根据这个key get到的node如果是空,返回-1, 如果不为空 返回node的key,并更新这个node的频率
2. put(): 如果nodeMAP包含这个key,那么就更新对应node的值,并且更新node频率; 如果不包含这个key,那么要新建一个node,加到nodeMap里,同时判断 如果这时候没有空间了,就把freqMap 里freq min那一个list的最后一个删掉,并且如果最后一个node不是null,删掉他在nodeMap的entry,size--, 如果有空间,直接加到对应的lis里。 min 设为1
update node freq
找到node原来的freq list,从中删除,如果这个freq是1,删掉后list为空了,那么更新最小频率
把他加到对应频率的fre list里,如果没哟 就新建