LRU Cache

来源:互联网 发布:美国普通程序员工资 编辑:程序博客网 时间:2024/06/05 19:43

思路:题目要求查找和插入操作都是O(1)的复杂度,所以要针对这个要求,设计合适的数据结构

1、题目要求最近使用的,放到最前面,因此get()会触发位置调整的操作,针对这一需求,比较合适的数据结构是双向链表,这里有一个小技巧,当需要将链表中某项移到最前面时,可以先删除,再重新在前面插入相应数据,而不是将其移动到最前面。

2、get和put都会涉及查询操作,如果所有的数据都以list存储,那么查询将是遍历操作,时间复杂度达不到要求。因此,要对查询操作设计辅助的数据结构,hash表非常适合,c++中是unordered_map.

3、list存储key值,用以快速调整相对位置;unordered_map以key为键值,以value和key在list中的迭代器作为值。查询操作是,通过key和unordered_map就可以知道相应的value和在list中的位置,对于get就可以返回value,并调整list中的位置(删除key,再在前面插入key);对于put先查询,如果存在,则更改value,调整list位置,如果不存在则插入新数据。插入新数据有两种情况,达到了最大容量,则通过list获取最后一个key,通过此key删除unordered_map中对应数据,并将list中的key也删除。然后就可以在list前面添加新的key,在unordered_map插入新的数据相关信息。


题目地址:https://leetcode.com/problems/lru-cache/description/

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?

#include <iostream>#include <algorithm>#include <vector>#include <unordered_map>#include <queue>#include <string>#include<list>using namespace std;class LRU{private:typedef list<int> LI;typedef pair<int, LI::iterator> LII;typedef unordered_map<int, LII> Unmap;LI lis;Unmap mymap;int cap;public:LRU();LRU(int _cap);int put(int key, int val);int get(int key);};LRU::LRU(){cap = 0;}LRU::LRU(int _cap){cap = _cap;}int LRU::put(int key, int val){Unmap::iterator ite = mymap.find(key);if (ite != mymap.end()){lis.erase((ite->second).second);lis.push_front(key);ite->second.first = val;}else{if (lis.size() == cap){mymap.erase(lis.back());lis.pop_back();}lis.push_front(key);mymap[key] = LII(val, lis.begin());}return 0;}int LRU::get(int key){Unmap::iterator ite = mymap.find(key);if (ite == mymap.end()) return -1;else{lis.erase(ite->second.second);lis.push_front(key);ite->second.second = lis.begin();return ite->first;}}int main(){LRU cache = LRU(2);cache.put(1, 1);cache.put(2, 2);cout<<cache.get(1)<<endl;       // returns 1cache.put(3, 3);                // evicts key 2cout<<cache.get(2)<<endl;       // returns -1 (not found)cache.put(4, 4);                // evicts key 1cout << cache.get(1) << endl;   // returns -1 (not found)cout << cache.get(3) << endl;   // returns 3cout << cache.get(4) << endl;   // returns 4system("pause");return 0;}


原创粉丝点击