460. LFU Cache
来源:互联网 发布:sql select like语句 编辑:程序博客网 时间:2024/06/06 07:06
1、题目描述
设计一个LFU的缓存机制。实现get和put函数。
2、思路
用map m记录cache中每个键值对。
用map rec记录每个键被访问的时间戳。
用map fre记录每个键被访问的次数。
get函数:如果在m中能找到key,则返回,且更新时间戳和频率;若找不到,则返回-1.
普通函数:如果m中能找到key,则更新key对应值,以及时间戳和频率;
如果找不到,若cache没满,则直接插入键值对,和对应的时间戳对和频率。
如果cache满了,则找到频率最小的那个key,把它在m、fre、rec中的记录删除,
再插入新的键值对,时间戳对、频率。
3、代码
class LFUCache {public: map<int,int>m; map<int,int>fre; map<int,int>rec; int t; int n; int c; LFUCache(int capacity) { t=0; n=0; c=capacity; } int get(int key) { t++; if(c==0) return -1; if(m.find(key)==m.end()) return -1; else{ rec[key]=t; fre[key]++; return m[key]; } } void put(int key, int value) { if(c==0) return ; t++; if(n>0&&m.find(key)!=m.end()){ m[key]=value; fre[key]++; rec[key]=t; } else{ if(n<c){ n++; m[key]=value; fre[key]++; rec[key]=t; } else{ map<int,int>::iterator it = fre.begin(); int k = -1,fremin = INT_MAX; for(;it!=fre.end();it++){ if(it->second < fremin){ k = it->first; fremin = it->second; } else if(it->second == fremin && rec[it->first] < rec[k]){ k = it->first; } } it = m.find(k); m.erase(it); it = fre.find(k); fre.erase(it); it = rec.find(k); rec.erase(it); m[key]=value; fre[key]++; rec[key]=t; } } }};
阅读全文
0 0
- LeetCode 460. LFU Cache
- LeetCode 460. LFU Cache
- 460. LFU Cache
- 460. LFU Cache
- [LeetCode]460. LFU Cache
- Leetcode 460. LFU Cache
- Leetcode 460. LFU Cache
- leetcode 460. LFU Cache
- LeetCode 460. LFU Cache
- 460. LFU Cache
- leetcode 146. LRU Cache 460. LFU Cache
- LFU Cache
- LFU Cache
- 460. LFU Cache O(1)算法 C++
- [Leetcode] 460. LFU Cache 解题报告
- LFU cache Java
- 460LFU Cache
- [LeetCode] LFU Cache
- 雇员管理系统-SSH版(四)
- 是那行代码,彻底改变了程序员的世界?
- 机房收费系统---导出Excel表
- c结构之位域bit field
- unittest框架介绍
- 460. LFU Cache
- 收集各种算法比较清晰的讲解
- 腾讯自然语言处理实习岗面经
- 加密
- ubuntu下Samba服务器的搭建
- 第四章 键值对操作(二)
- 使用Markdown
- 图书管理系统代码
- 一看就懂的Redis简单操作及简介