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();
}
};