# 【LeetCode】 146. LRU Cache
## Description
> 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不存在。如果快取已經到它的上限了,使最久未使用的項目失效並加入新的項目。
## Example:
```
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
```
## Solution
* 注意:這題比起常見的題目,需要看懂C++中Class的運作與使用方式。
* 這題有學過OS的應該不陌生,基本上就是要實作系統排程中的LRU演算法。
* 這邊使用一個變數`time`來記錄每個資料最後被使用的時間;而每次動作都會讓`time++`。
* 接著就是用`pair`來綁時間和值綁起來,再用`map`把`value`和`pair`綁起來。
* 容量不足的時候,使用`min_element`去找到並移除`time`最小的項目。
---
* 這題解出來的時間不太漂亮,以下可以強化速度:
* `get`使用hash加速,在這邊的`unordered_map`就是。
* `put`的部分可以使用linked-list來實作,根據`time`來串起來的話,就可以直接在頭尾加入移除。
* 因為想不太到C++的STL怎麼用比較好,就沒有實作了。
### Code
```C++=1
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);
*/
```
###### tags: `LeetCode` `C++`