leetcode 460. LFU Cache

﹏ヽ暗。殇╰゛Y 2022-06-04 10:26 217阅读 0赞

Design and implement a data structure for Least Frequently Used (LFU) 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 reaches its capacity, it should invalidate the least frequently used item before inserting a new item. For the purpose of this problem, when there is a tie (i.e., two or more keys that have the same frequency), the least recently used key would be evicted.

Follow up:
Could you do both operations in O(1) time complexity?

Example:

LFUCache cache = new LFUCache( 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.get(3); // returns 3.
cache.put(4, 4); // evicts key 1.
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4

不喜欢这样的题,答案是参考网上的答案,就这么做吧

代码如下:

  1. class LFUCache
  2. {
  3. int size;
  4. int minfreq;
  5. int cap;
  6. map<int,pair<int,int>> m;//key to pair<value,freq>
  7. map<int,list<int>::iterator> mIter;//key to list location
  8. map<int,list<int>> fm;//freq to list
  9. public:
  10. LFUCache(int capacity)
  11. {
  12. cap=capacity;
  13. size=0;
  14. }
  15. int get(int key)
  16. {
  17. if(m.count(key)==0) return -1;
  18. fm[m[key].second].erase(mIter[key]);//删除key在fm原来的位置
  19. m[key].second++;//频率加一
  20. fm[m[key].second].push_back(key);//按照频率,放在新的位置上
  21. mIter[key]=--fm[m[key].second].end();//存储key现在所在的链表例=里的位置
  22. if(fm[minfreq].size()==0)
  23. minfreq++;
  24. return m[key].first;
  25. }
  26. void put(int key, int value)
  27. {
  28. if(cap<=0) return;
  29. int storedValue=get(key);
  30. if(storedValue!=-1)//若以前已经存在过
  31. {
  32. m[key].first=value;
  33. return;
  34. }//否则,
  35. if(size>=cap)//可能要根据LFU删掉一个元素
  36. {
  37. m.erase(fm[minfreq].front());
  38. mIter.erase(fm[minfreq].front());
  39. fm[minfreq].pop_front();
  40. size--;
  41. }
  42. m[key]={value,1};
  43. fm[1].push_back(key);
  44. mIter[key]=--fm[1].end();
  45. minfreq=1;
  46. size++;
  47. }
  48. };

发表评论

表情:
评论列表 (有 0 条评论,217人围观)

还没有评论,来说两句吧...

相关阅读

    相关 LFU cache

    LFU 请你为 最不经常使用(LFU)缓存算法设计并实现数据结构。它应该支持以下操作:get 和 put。 get(key) - 如果键存在于缓存中,则获