題目:
運用你所掌握的數據結構,設計和實現一個 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
思路:
list<pair<int,int>> 是一個雙向鏈表,存儲鍵值(key,value),map<int,list<pair<int,int>>::iterator>>是用來存放key值所對應的list中的位置
list鏈表的開頭,是最近使用過的,當每次進行get()和put()操作時,我們就要更新。要注意的是,若(key1,value1)已經存在,當put(key1,value2)時,我們要直接修改value值,同時放到鏈表的開頭。
list鏈表的末尾,是最久使用過的,當容量滿時,就要將它替換出去,將最新的(key,value)放在鏈表開頭
代碼:
class LRUCache { private: int n; list<pair<int,int> > lis; unordered_map<int,list<pair<int,int>>::iterator> m; public: LRUCache(int capacity) { n = capacity; } int get(int key) { auto it = m.find(key); int ans = -1; if(it!=m.end()) { ans = it->second->second; lis.erase(it->second); lis.push_front(make_pair(key,ans)); it->second = lis.begin(); } return ans; } void put(int key, int value) { auto it = m.find(key); if(it!=m.end()) { lis.erase(it->second); lis.push_front(make_pair(key,value)); m[key] = lis.begin(); } else if(m.size()<n) { lis.push_front(make_pair(key,value)); m[key] = lis.begin(); } else { auto it = lis.end(); it--; m.erase(it->first); lis.erase(it); lis.push_front(make_pair(key,value)); it = lis.begin(); m[key] = it; } } }; /** * 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); */