LRU Cache -- leetcode
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.
基本思路:
用一个map处理查找问题。
用list维护按使用元素排序。将最近被访问的记录,总是移动到链表头。
list中存储的是[key, value],
而map中存储的是key, 以及在list中对应节点的iterator。
在将list中的元素移动到最前时,使用了splice函数。 此函数比先删除,再插入,要高效。
此代码在leetcode上实际执行时间为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_; };
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。