1. 程式人生 > >146.LRU快取機制

146.LRU快取機制

運用你所掌握的資料結構,設計和實現一個  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

class LRUCache { public:     LRUCache(int capacity) {         cap = capacity;     }          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;     }          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; };

/**  * 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);  */