題目: LeetCode - 146. LRU Cache
題目說明
建立一個類似快取記憶體的 Class,及對應的一些功能。
解題思路
使用 list<pair<int, int>>
儲存資料,再利用 unordered_map<int, list<pair<int, int>>::iterator>
達到減少時間複雜度的效果。
※ 對於 put
來說,如果資料已經滿了,那新的資料就要覆蓋最久沒有調用到的資料。
參考解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| class LRUCache { public: list<pair<int, int>> cache; unordered_map<int, list<pair<int, int>>::iterator> hash; int Cap;
LRUCache(int capacity) { Cap = capacity; } int get(int key) { auto it = hash.find(key); if(it == hash.end()) return -1; cache.splice(cache.begin(), cache, it->second); return it->second->second; } void put(int key, int value) { auto it = hash.find(key); if(it != hash.end()) { it->second->second = value; cache.splice(cache.begin(), cache, it->second); return; } if(cache.size() == Cap) { hash.erase(cache.back().first); cache.pop_back(); } cache.emplace_front(key, value); hash[key] = cache.begin(); } };
|
補充
splice()
的功能是串接 List。
emplace_front()
的功能和 push_front()
是一樣的,但是前者少了一個複製的動作,效率較高。
參考資料
花花酱 LeetCode 146. LRU Cache O(1)
list::splice()函数详解
STL - emplace 与 push 的区别
list::emplace_back - C++ Reference
list::splice - C++ Reference