算法描述:
Design and implement a data structure for . 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 1cache.put(3, 3); // evicts key 2cache.get(2); // returns -1 (not found)cache.put(4, 4); // evicts key 1cache.get(1); // returns -1 (not found)cache.get(3); // returns 3cache.get(4); // returns 4
解题思路:时间复杂度为O(1),所以为了便于查找必须采用hash尽力映射。而为了便于插入删除,采用双端链表存储数据。需要注意的是容量不够需要删除尾部元素。此外,查到map中有key存在,需要替换value值,否则有些case过不去。
struct DoubleListNode{ int key; int val; DoubleListNode* prev; DoubleListNode* next; DoubleListNode(int x, int y): key(x), val(y), prev(nullptr), next(nullptr){}};class LRUCache {public: LRUCache(int capacity) : _capacity(capacity) { head->next=tail; tail->prev=head; } int get(int key) { if(dMap.find(key)==dMap.end()){ return -1; }else{ dMap[key]->prev->next = dMap[key]->next; dMap[key]->next->prev = dMap[key]->prev; dMap[key]->next = head->next; head->next->prev = dMap[key]; head->next = dMap[key]; dMap[key]->prev = head; return dMap[key]->val; } } void put(int key, int value) { if(dMap.find(key) == dMap.end()){ if(_capacity==0){ DoubleListNode* temp = tail->prev; tail->prev=tail->prev->prev; tail->prev->next=tail; dMap.erase(temp->key); _capacity++; } dMap[key] = new DoubleListNode(key, value); dMap[key]->next=head->next; head->next->prev = dMap[key]; head->next=dMap[key]; dMap[key]->prev=head; _capacity--; }else{ dMap[key]->prev->next = dMap[key]->next; dMap[key]->next->prev = dMap[key]->prev; dMap[key]->next=head->next; head->next->prev = dMap[key]; head->next = dMap[key]; dMap[key]->prev = head; dMap[key]->val=value; } }private: unordered_mapdMap; int _capacity; DoubleListNode* head = new DoubleListNode(-1,-1); DoubleListNode* tail = new DoubleListNode(-1,-1);};