運用你所掌握的數據結構,設計和實現一個??LRU (最近最少使用) 緩存機制。它應該支持以下操作: 獲取數據 get 和 寫入數據 put 。
獲取數據 get(key) - 如果密鑰 (key) 存在于緩存中,則獲取密鑰的值(總是正數),否則返回 -1。
寫入數據 put(key, value) - 如果密鑰不存在,則寫入其數據值。當緩存容量達到上限時,它應該在寫入新數據之前刪除最近最少使用的數據值,從而為新的數據值留出空間。進階:
你是否可以在?O(1) 時間復雜度內完成這兩種操作?
示例:
LRUCache cache = new LRUCache( 2 /* 緩存容量 */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); ? ? ? // 返回 ?1
cache.put(3, 3); ? ?// 該操作會使得密鑰 2 作廢
cache.get(2); ? ? ? // 返回 -1 (未找到)
cache.put(4, 4); ? ?// 該操作會使得密鑰 1 作廢
cache.get(1); ? ? ? // 返回 -1 (未找到)
cache.get(3); ? ? ? // 返回 ?3
cache.get(4); ? ? ? // 返回 ?4來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/lru-cache
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
解法:?
#include <iostream>
#include <unordered_map>
#include <memory>
#include <list>
#include <utility>
using namespace std;class LRUCache
{
public:LRUCache(int capacity) //緩存容量{cap = capacity;}/*存在于緩存中,則獲取密鑰的值(總是正數),否則返回 -1。獲取數據 get(key) - 如果密鑰 (key) */int get(int key) {auto it = m.find(key);if (it == m.end()) return -1;l.splice(l.begin(), l, it->second);return it->second->second;}/*寫入數據 put(key, value) - 如果密鑰不存在,則寫入其數據值。當緩存容量達到上限時,它應該在寫入新數據之前刪除最近最少使用的數據值,從而為新的數據值留出空間*/void put(int key, int value){auto it = m.find(key);if (it != m.end())l.erase(it->second);l.push_front(make_pair(key, value));m[key] = l.begin();if (m.size() > cap){int k = l.rbegin()->first;l.pop_back();m.erase(k);}}private:int cap;list<pair<int/*關鍵字*/, int>> l;unordered_map<int/*關鍵字*/, list<pair<int, int>>::iterator> m;
};int main()
{LRUCache cache(2 /* 緩存容量 */);cache.put(1, 1);cache.put(2, 2);cout << cache.get(1) << endl; // 返回 1cache.put(3, 3); // 該操作會使得密鑰 2 作廢cout << cache.get(2) << endl; // 返回 -1 (未找到)cache.put(4, 4); // 該操作會使得密鑰 1 作廢cout << cache.get(1) << endl; // 返回 -1 (未找到)cout << cache.get(3) << endl; // 返回 3cout << cache.get(4) << endl; // 返回 4return 0;
}
?