首页 > 代码库 > 146. LRU Cache
146. LRU Cache
146. LRU Cache
- Total Accepted: 109086
- Total Submissions: 675208
- Difficulty: Hard
- Contributors: Admin
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and put
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.put(key, value)
- Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LRUCache cache = new LRUCache( 2 /* capacity */ ); cache.put(1, 1); cache.put(2, 2); cache.get(1); // returns 1 cache.put(3, 3); // evicts key 2 cache.get(2); // returns -1 (not found) cache.put(4, 4); // evicts key 1 cache.get(1); // returns -1 (not found) cache.get(3); // returns 3 cache.get(4); // returns 4
We need two data structures:
list: list<pair<int, int>>//record the order of objects
hashmap: map<int, list<pair<int, int>>::iterator>//mapping the relationship between key and objects
//must use the iterator, otherwise the splice function will not work
Functions:
Set(key, value)//If the object exists int the map, erase it in the list first, and then push the object from the front. Set m[key] = l.front();
//if the size of map is larger than capacity, erase the object both from list and map;
Get(key)//If the objects do not exist in map, return -1;
//The only change is the order in the list.
//to_list.splice(position, from_list, iterator)
1 class LRUCache { 2 public: 3 LRUCache(int capacity) { 4 cap = capacity; 5 } 6 7 int get(int key) { 8 auto it = m.find(key); 9 if(it == m.end()) return -1;//not find 10 l.splice(l.begin(), l, it -> second);//move it in l to l.begin(); 11 return it -> second -> second; 12 } 13 14 void put(int key, int value) { 15 auto it = m.find(key); 16 if(it != m.end()) l.erase(it -> second); 17 //l.push_front(it -> second); 18 l.push_front(make_pair(key, value)); 19 m[key] = l.begin(); 20 if(m.size() > cap){ 21 auto k = l.rbegin() -> first;//要存int类型 不然指针unsafe 因为后面list要pop_back 22 l.pop_back(); 23 //m.erase(k -> first); 24 m.erase(k); 25 } 26 } 27 private: 28 int cap; 29 list<pair<int, int>> l;//record the order of least recently used 30 map<int, list<pair<int, int>>::iterator> m;//hashmap 一定要iterator 31 }; 32 33 /** 34 * Your LRUCache object will be instantiated and called as such: 35 * LRUCache obj = new LRUCache(capacity); 36 * int param_1 = obj.get(key); 37 * obj.put(key,value); 38 */
146. LRU Cache