Design and implement a data structure for Least Recently Used (LRU) 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 reached its capacity, it should invalidate the least recently used item before inserting a new item.
The cache is initialized with a positive capacity.
Follow up:
Could you do both operations in O(1) time complexity?
設計並實作一個稱作最久未使用(LRU)快取的資料結構。它支援以下運算:get 和 put。
- get(key) - 如果該key存在就取得該key的value(確保它是正數),否則回傳-1。
- put(key, value) - 賦值或是插入一個value當該key不存在。如果快取已經到它的上限了,使最久未使用的項目失效並加入新的項目。
LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
time
來記錄每個資料最後被使用的時間;而每次動作都會讓time++
。pair
來綁時間和值綁起來,再用map
把value
和pair
綁起來。min_element
去找到並移除time
最小的項目。get
使用hash加速,在這邊的unordered_map
就是。put
的部分可以使用linked-list來實作,根據time
來串起來的話,就可以直接在頭尾加入移除。
class LRUCache {
public:
int time;
int c;
unordered_map<int, pair<int, int>> m;
LRUCache(int capacity) {
time = 0;
c = capacity;
}
int get(int key) {
this->time++;
if(m.count(key) == 0)
{
return -1;
}
else
{
m[key].second = this->time;
return m[key].first;
}
}
void put(int key, int value) {
this->time++;
pair<int, int> p(value, this->time);
m[key] = p;
if(m.size() > c)
{
m.erase(min_element(m.begin(), m.end(),
[](const auto& l, const auto& r) { return l.second.second < r.second.second; }));
}
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
LeetCode
C++