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 ('ll 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 is reached its capacity, it should invalidate the least recently used item before inserting a new item.
Basic ideas:
Work with a map to find the problem.
Use list maintenance to sort by using elements. The records that are recently accessed are always moved to the linked list header.
The list stores [key, value],
The map stores the key, as well as the iterator of the corresponding node in the list.
The splice function is used when the elements in the list are moved to the front. This function is more efficient than first deleting and then inserting.
The actual execution time for this code on Leetcode is 160ms.
Class Lrucache{public: LRUCache (int capacity): Capacity_ (capacity) { } int get (int key) { Auto iter = Cache_.find (key); if (iter = = Cache_.end ()) return-1; Lru_.splice (Lru_.begin (), lru_, Iter->second); Return iter->second->second; } void set (int key, int value) { if (get (key)! =-1) { Lru_.front (). second = value; return; } if (lru_.size () = = capacity_) { cache_.erase (Lru_.back (). first); Lru_.pop_back (); } Lru_.push_front (Make_pair (key, value)); Cache_[key] = Lru_.begin (); } Private: typedef list<pair<int, int> > list_t; typedef unordered_map<int, list_t::iterator> map_t; list_t lru_; map_t cache_; const int capacity_;};
LRU Cache--Leetcode