146. LRU缓存机制
運(yùn)用你所掌握的數(shù)據(jù)結(jié)構(gòu),設(shè)計(jì)和實(shí)現(xiàn)一個(gè)??LRU (最近最少使用) 緩存機(jī)制。它應(yīng)該支持以下操作: 獲取數(shù)據(jù) get 和 寫入數(shù)據(jù) put 。
獲取數(shù)據(jù) get(key) - 如果密鑰 (key) 存在于緩存中,則獲取密鑰的值(總是正數(shù)),否則返回 -1。
寫入數(shù)據(jù) put(key, value) - 如果密鑰不存在,則寫入其數(shù)據(jù)值。當(dāng)緩存容量達(dá)到上限時(shí),它應(yīng)該在寫入新數(shù)據(jù)之前刪除最近最少使用的數(shù)據(jù)值,從而為新的數(shù)據(jù)值留出空間。
進(jìn)階:
你是否可以在?O(1) 時(shí)間復(fù)雜度內(nèi)完成這兩種操作?
示例:
LRUCache cache = new LRUCache( 2 /* 緩存容量 */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); ? ? ? // 返回 ?1
cache.put(3, 3); ? ?// 該操作會(huì)使得密鑰 2 作廢
cache.get(2); ? ? ? // 返回 -1 (未找到)
cache.put(4, 4); ? ?// 該操作會(huì)使得密鑰 1 作廢
cache.get(1); ? ? ? // 返回 -1 (未找到)
cache.get(3); ? ? ? // 返回 ?3
cache.get(4); ? ? ? // 返回 ?4
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/lru-cache
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
解法:?
#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ù)值。當(dāng)緩存容量達(dá)到上限時(shí),它應(yīng)該在寫入新數(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/*關(guān)鍵字*/, int>> l;unordered_map<int/*關(guān)鍵字*/, 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); // 該操作會(huì)使得密鑰 2 作廢cout << cache.get(2) << endl; // 返回 -1 (未找到)cache.put(4, 4); // 該操作會(huì)使得密鑰 1 作廢cout << cache.get(1) << endl; // 返回 -1 (未找到)cout << cache.get(3) << endl; // 返回 3cout << cache.get(4) << endl; // 返回 4return 0; }?
總結(jié)
以上是生活随笔為你收集整理的146. LRU缓存机制的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 爱上男主播剧情介绍
- 下一篇: 103. 二叉树的锯齿形层次遍历