LRU Cache

描述

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.

分析

为了使查找、插入和删除都有较高的性能,这题的关键是要使用一个双向链表和一个HashMap,因为:

  • HashMap保存每个节点的地址,可以基本保证在O(1)时间内查找节点
  • 双向链表能后在O(1)时间内添加和删除节点,单链表则不行
    具体实现细节:

  • 越靠近链表头部,表示节点上次访问距离现在时间最短,尾部的节点表示最近访问最少

  • 访问节点时,如果节点存在,把该节点交换到链表头部,同时更新hash表中该节点的地址
  • 插入节点时,如果cache的size达到了上限capacity,则删除尾部节点,同时要在hash表中删除对应的项;新节点插入链表头部
    LRU Cche
    Figure: LRU Cche

代码

C++的std::list 就是个双向链表,且它有个 splice()方法,O(1)时间,非常好用。

  1. // LRU Cache
  2. // 时间复杂度O(logn),空间复杂度O(n)
  3. class LRUCache{
  4. private:
  5. struct CacheNode {
  6. int key;
  7. int value;
  8. CacheNode(int k, int v) :key(k), value(v){}
  9. };
  10. public:
  11. LRUCache(int capacity) {
  12. this->capacity = capacity;
  13. }
  14. int get(int key) {
  15. if (cacheMap.find(key) == cacheMap.end()) return -1;
  16. // 把当前访问的节点移到链表头部,并且更新map中该节点的地址
  17. cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);
  18. cacheMap[key] = cacheList.begin();
  19. return cacheMap[key]->value;
  20. }
  21. void set(int key, int value) {
  22. if (cacheMap.find(key) == cacheMap.end()) {
  23. if (cacheList.size() == capacity) { //删除链表尾部节点(最少访问的节点)
  24. cacheMap.erase(cacheList.back().key);
  25. cacheList.pop_back();
  26. }
  27. // 插入新节点到链表头部, 并且在map中增加该节点
  28. cacheList.push_front(CacheNode(key, value));
  29. cacheMap[key] = cacheList.begin();
  30. } else {
  31. //更新节点的值,把当前访问的节点移到链表头部,并且更新map中该节点的地址
  32. cacheMap[key]->value = value;
  33. cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);
  34. cacheMap[key] = cacheList.begin();
  35. }
  36. }
  37. private:
  38. list<CacheNode> cacheList; // doubly linked list
  39. unordered_map<int, list<CacheNode>::iterator> cacheMap;
  40. int capacity;
  41. };

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/linear-list/linked-list/lru-cache.html