Try   HackMD

【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來綁時間和值綁起來,再用mapvaluepair綁起來。
  • 容量不足的時候,使用min_element去找到並移除time最小的項目。

  • 這題解出來的時間不太漂亮,以下可以強化速度:
    • get使用hash加速,在這邊的unordered_map就是。
    • put的部分可以使用linked-list來實作,根據time來串起來的話,就可以直接在頭尾加入移除。
  • 因為想不太到C++的STL怎麼用比較好,就沒有實作了。

Code

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++