Leetcode No.146 ****
生活随笔
收集整理的這篇文章主要介紹了
Leetcode No.146 ****
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
運用你所掌握的數據結構,設計和實現一個??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參考博客:http://www.cnblogs.com/grandyang/p/4587511.html
解答:通過構建一個list表,內容為pair<int,int>,即鍵-值對,用于存放當前的緩存值。同時構建一個Hash表,
unordered_map<int, list<pair<int,int>>::iterator> m 用于存放key-list內容,目的是用于快速查詢鍵值對。
get函數:查詢哈希表中是否有輸入的key值,沒有則返回 -1 ,否則返回相應的值,并用list.splice更新當前鍵值對在list最前處。
put函數:如果存在鍵值對,那么則在list中刪除該鍵值對。將新輸入的鍵值對放在list的最前處,并同時更新Hash表中的鍵值對。
如果容量已經超過最大值,那么將最不常用的鍵值對(位于list最后處)彈出。同時刪除Hash表中的鍵值對。
函數說明:
【1】unordered_map<int, list<pair<int,int>>::iterator> m;
auto it=m.find(key); 相當于 list<pair<int,int>>::iterator it;
【2】it->second 表示取到了pair<int,int>
【3】l.splice(l.begin(),l, it->second); 表示將pair<int,int>放置在list的最前端,其余順序不變。
class LRUCache { public:LRUCache(int capacity) {this->capacity=capacity; }int get(int key) {// list<pair<int,int>>::iterator it;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) {// list<pair<int,int>>::iterator it;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 ((int)m.size() > capacity) {int k = l.rbegin()->first;l.pop_back();m.erase(k);}}private:int capacity;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);*/
?
轉載于:https://www.cnblogs.com/2Bthebest1/p/10853521.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的Leetcode No.146 ****的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java继承上机作业
- 下一篇: datagrid 的标题的内容不对应整