Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and set
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.set(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.
思路:
挺诡异的,明明写法一样,但是总是超时,以后再看是怎么回事吧。
另外auto的用法不错。
代码:
1 class LRUCache 2 { 3 int m_Capacity; 4 unordered_map<int, int> m_Cache; 5 list<int> m_Recently; 6 7 void touch(int key) 8 { 9 auto kiter = find(begin(m_Recently), end(m_Recently), key); 10 m_Recently.erase(kiter); 11 m_Recently.push_front (key); 12 } 13 public: 14 LRUCache (int capacity) : m_Capacity (capacity) 15 {} 16 17 int get (int key) 18 { 19 auto iter = m_Cache.find (key); 20 if (iter == end(m_Cache)) 21 return -1; // not found 22 else 23 { 24 touch(key); 25 return iter->second; 26 } 27 } 28 29 void set (int key, int value) 30 { 31 auto iter = m_Cache.find (key); 32 33 if (iter == end(m_Cache)) 34 { 35 if (m_Cache.size() >= m_Capacity) 36 { 37 int last = m_Recently.back(); 38 m_Recently.pop_back(); 39 m_Cache.erase (last); 40 } 41 m_Recently.push_front(key); 42 } 43 44 m_Cache[key] = value; 45 touch(key); 46 } 47 };