146. LRU缓存机制
運用你所掌握的數(shù)據(jù)結構,設計和實現(xiàn)一個??LRU (最近最少使用) 緩存機制。它應該支持以下操作: 獲取數(shù)據(jù) get 和 寫入數(shù)據(jù) put 。
獲取數(shù)據(jù) get(key) - 如果密鑰 (key) 存在于緩存中,則獲取密鑰的值(總是正數(shù)),否則返回 -1。
寫入數(shù)據(jù) put(key, value) - 如果密鑰不存在,則寫入其數(shù)據(jù)值。當緩存容量達到上限時,它應該在寫入新數(shù)據(jù)之前刪除最近最少使用的數(shù)據(jù)值,從而為新的數(shù)據(jù)值留出空間。
進階:
你是否可以在?O(1) 時間復雜度內(nèi)完成這兩種操作?
示例:
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
著作權歸領扣網(wǎng)絡所有。商業(yè)轉載請聯(lián)系官方授權,非商業(yè)轉載請注明出處。
解法:?
#include <iostream> #include <unordered_map> #include <memory> #include <list> #include <utility> using namespace std;class LRUCache { public:LRUCache(int capacity) //緩存容量{cap = capacity;}/*存在于緩存中,則獲取密鑰的值(總是正數(shù)),否則返回 -1。獲取數(shù)據(jù) 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;}/*寫入數(shù)據(jù) put(key, value) - 如果密鑰不存在,則寫入其數(shù)據(jù)值。當緩存容量達到上限時,它應該在寫入新數(shù)據(jù)之前刪除最近最少使用的數(shù)據(jù)值,從而為新的數(shù)據(jù)值留出空間*/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; }?
總結
以上是生活随笔為你收集整理的146. LRU缓存机制的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 爱上男主播剧情介绍
- 下一篇: 暗区突围手游挑战农场男团怎么撤离