146. LRU Cache[hard]
来源:互联网 发布:app数据查询 编辑:程序博客网 时间:2024/05/16 08:27
146. LRU Cache
- Total Accepted: 86514
- Total Submissions: 545459
- Difficulty: Hard
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:get
and set
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.set(key, value)
- Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
很简单的题目
用三个map分别装:
1、Cache里面的数据
2、每个数据最后的更新时间(used_time)
3、每个时间分别对哪个数据进行了操作(note)
对于每一个操作维护好这三个map就行
class LRUCache{private: int Capacity; int Clock = 0; map <int , int > Cache; map <int , int > used_time; map <int , int > note;public: LRUCache(int capacity) { Capacity = capacity; Clock = 0; } void note_check() { while( Cache.count( note.begin()->second ) == 0 || used_time[ note.begin()->second ] != note.begin()->first ) note.erase( note.begin() ); } void check() { note_check(); while( Cache.size() > Capacity ) { int x = note.begin()->second; Cache.erase(x); used_time.erase(x); note.erase( note.begin() ); note_check(); } } int get(int key) { ++Clock; if(Cache.count(key)!=0) { used_time[key] = Clock; note[Clock] = key; note_check(); return Cache[key]; } return -1; } void set(int key, int value) { ++Clock; Cache[key] = value; used_time[key] = Clock; note[Clock] = key; check(); }};
0 0
- [hard]146. LRU Cache
- 146. LRU Cache[hard]
- Leetcode 146. LRU Cache (Hard) (cpp)
- Hard 146题 LRU Cache
- 【Leetcode-hard-146】LRU Cache
- 4.【Hard】LRU Cache--Time Limit Exceeded
- LeetCode 146. LRU Cache
- [leetcode] 146.LRU Cache
- 146. LRU Cache
- leetcode 146. LRU Cache
- Leetcode 146. LRU Cache
- Leetcode - 146. LRU Cache
- Leetcode 146. LRU Cache
- [leetcode] 146. LRU Cache
- Leetcode 146. LRU Cache
- leetcode 146. LRU Cache
- LeetCode-146. LRU Cache
- LeetCode 146. LRU Cache
- android缓存系列:动手封装DiskLruCache
- SnackBar(支持上下显示,兼容低版本)
- Android Rxjava之just方法的使用
- 多线程中的基本概念
- 模拟 优先队列(hdu 5437)
- 146. LRU Cache[hard]
- 普通素数筛法
- 3.3 垃圾收集算法
- codeforces 682D(DP)
- Phpstorm配置git版本控制器
- Java后台学习之---cookie和session学习
- linux定时任务crontab自动备份mysql数据库(ssh/php)
- Struts2.0学习---第一个程序
- android开发实用工具