LFU缓存

请你为 最不经常使用(LFU)缓存算法设计并实现数据结构。它应该支持以下操作:get 和 put。

get(key) - 如果键存在于缓存中,则获取键的值(总是正数),否则返回 -1。 put(key, value) - 如果键不存在,请设置或插入值。当缓存达到其容量时,则应该在插入新项之前,使最不经常使用的项无效。在此问题中,当存在平局(即两个或更多个键具有相同使用频率)时,应该去除 最近 最少使用的键。 「项的使用次数」就是自插入该项以来对其调用 get 和 put 函数的次数之和。使用次数会在对应项被移除后置为 0 。

示例:

LFUCache cache = new LFUCache( 2 / capacity (缓存容量) / );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 去除 key 2
cache.get(2); // 返回 -1 (未找到key 2)
cache.get(3); // 返回 3
cache.put(4, 4); // 去除 key 1
cache.get(1); // 返回 -1 (未找到 key 1)
cache.get(3); // 返回 3
cache.get(4); // 返回 4


  1. struct Node {
  2. int cnt, time, key, value;
  3. Node(int _cnt, int _time, int _key, int _value):cnt(_cnt), time(_time), key(_key), value(_value){}
  4. bool operator < (const Node& rhs) const {
  5. return cnt == rhs.cnt ? time < rhs.time : cnt < rhs.cnt;
  6. }
  7. };
  8. class LFUCache {
  9. // 缓存容量,时间戳
  10. int capacity, time;
  11. unordered_map<int, Node> key_table;
  12. set<Node> S;
  13. public:
  14. LFUCache(int _capacity) {
  15. capacity = _capacity;
  16. time = 0;
  17. key_table.clear();
  18. S.clear();
  19. }
  20. int get(int key) {
  21. if (capacity == 0) return -1;
  22. auto it = key_table.find(key);
  23. // 如果哈希表中没有键 key,返回 -1
  24. if (it == key_table.end()) return -1;
  25. // 从哈希表中得到旧的缓存
  26. Node cache = it -> second;
  27. // 从平衡二叉树中删除旧的缓存
  28. S.erase(cache);
  29. // 将旧缓存更新
  30. cache.cnt += 1;
  31. cache.time = ++time;
  32. // 将新缓存重新放入哈希表和平衡二叉树中
  33. S.insert(cache);
  34. it -> second = cache;
  35. return cache.value;
  36. }
  37. void put(int key, int value) {
  38. if (capacity == 0) return;
  39. auto it = key_table.find(key);
  40. if (it == key_table.end()) {
  41. // 如果到达缓存容量上限
  42. if (key_table.size() == capacity) {
  43. // 从哈希表和平衡二叉树中删除最近最少使用的缓存
  44. key_table.erase(S.begin() -> key);
  45. S.erase(S.begin());
  46. }
  47. // 创建新的缓存
  48. Node cache = Node(1, ++time, key, value);
  49. // 将新缓存放入哈希表和平衡二叉树中
  50. key_table.insert(make_pair(key, cache));
  51. S.insert(cache);
  52. }
  53. else {
  54. // 这里和 get() 函数类似
  55. Node cache = it -> second;
  56. S.erase(cache);
  57. cache.cnt += 1;
  58. cache.time = ++time;
  59. cache.value = value;
  60. S.insert(cache);
  61. it -> second = cache;
  62. }
  63. }
  64. };