题目描述:
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
实现一个LRU缓存,要求可以插入、查找,并且保证两种操作都是O(1)的时间复杂度。由于要求查找的时间复杂度为O(1),所以需要一个哈希表来存储每个元素和对应的位置,同时一旦查找、或者插入一个元素,这个元素就被更新为最新元素,而且如果元素超过LRU的容量就要把最近最不常用的元素删除,所以一个采用双向链表(STL中的list就是双向链表),最新元素放置于表头,最不常用元素放置于表尾,而且由于LRU缓存中一个元素的key表示搜索的键值,value表示对应的数值,那么双向链表中元素也应该是一个pair(key,value)。每次查找、插入一个元素,都要在O(1)的时间复杂度内把这个元素移动到表头,可以利用l.splice(l.begin(),l,it)实现,其中splice函数有三种形式:
①l.splice(iterator position,list<T,Allocator>& x );
②l.splice(iterator position, list<T,Allocator>& x,iterator i );
③l.splice(iterator position,list<T,Allocator>& x,iterator first, iterator last );
①表示将链表x全部插入到链表l中position之前;②表示将链表x中迭代器i指向的元素删除,并且插入到链表l中position之前;③表示将链表x中从迭代器first到last这一段链表删除,并且插入到链表l中position之前。list的splice函数时间复杂度为O(1),但是list的size函数是O(n)的时间复杂度。
class LRUCache {
public:
LRUCache(int capacity) {
len=capacity;
}
int get(int key) {
if(hash.count(key)==0) return -1;
list<pair<int,int>>::iterator it=hash[key];
l.splice(l.begin(),l,it);
return l.front().second;
}
void put(int key, int value) {
if(hash.count(key)==0)
{
l.push_front(pair<int,int>(key,value));
hash[key]=l.begin();
}
else
{
list<pair<int,int>>::iterator it=hash[key];
it->second=value;
l.splice(l.begin(),l,it);
}
if(hash.size()>len)
{
int x=l.back().first;
l.pop_back();
hash.erase(x);
}
}
private:
int len;
list<pair<int,int>> l;
unordered_map<int,list<pair<int,int>>::iterator> hash;
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/
本文介绍了一种高效实现LRU缓存的方法,通过结合哈希表与双向链表,确保了get与put操作都能达到O(1)的时间复杂度。文章详细解释了数据结构的设计思路与具体实现细节。
976

被折叠的 条评论
为什么被折叠?



