LFU Cache解題報告

Description:

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

Link:

https://leetcode.com/problems/lfu-cache/#/description

解題方法:

想要在O(1)的時候內(nèi)完成get()由key映射到node的哈希表keyToNode是不可免的。
當(dāng)內(nèi)存滿時,需要刪除使用頻率最少的數(shù),如果有幾個相同的數(shù)則刪除最早的那個。所以可以想到要把相同頻率的數(shù)歸納到一起,我們還需要另一個由頻率映射到list的另一個哈希表freToList。每個list里面儲存的是相同頻率的不同node或key。
當(dāng)使用get()函數(shù)時,我們需要專門找到某個node,使其頻率+1。為了能在O(1)的時候內(nèi)完成這個操作。每個node除了儲存value,頻率以外,還需要儲存的是其在freToList里某個list的迭代器。

由此,在O(1)時間完成頻率的更新和加減node都可以實(shí)現(xiàn)了。最后一步問題很容易讓人想不明白:當(dāng)需要刪除最少使用的node時,如何得到最少頻率minFre從而在freTolist進(jìn)行操作?

有幾個需要認(rèn)清的細(xì)節(jié)可以解決這個問題:
1、當(dāng)有新的node加入的時候,minFre一定為1。
2、使minFre不為1的情況只有進(jìn)行get()成功的時候或者用put()更新一個node的value的時候。
3、以上兩個操作都不會使一個數(shù)的頻率進(jìn)行跳躍增長(即每次都只會讓一個數(shù)的頻率+1)。
由以上3點(diǎn)可以得出我們怎樣不會使minFre出錯的方法:
1、當(dāng)有新的數(shù)加入的時候,使minFre = 1
2、當(dāng)對一個數(shù)的頻率進(jìn)行更改后,如果freToList[minFre].size() == 0,那么minFre一定為minFre++

Tips:

使用list來儲存相同頻率的數(shù),每次從list的前面插入,要刪除時從list的后面刪除。這樣每次就會刪除最早的最少使用次數(shù)的node。
如果每次從后面插入那么迭代器不好賦值,原因如下:

Time Complexity:

O(1)

完整代碼:

class Node
{
public:
    int val;
    int fre;
    list<int>::iterator iter;
    Node(int v, int f): val(v), fre(f) {}   
};
class LFUCache 
{
private:
    unordered_map<int, Node*> keyToNode;
    unordered_map<int, list<int>> freToList;
    int capacity;
    int size;
    int minFre;
public:
    LFUCache(int capacity) 
    {
        size = 0;
        this->capacity = capacity;
    }
    
    int get(int key) 
    {
        if(keyToNode[key] == NULL)
            return -1;
        list<int>::iterator change = keyToNode[key]->iter;
        freToList[keyToNode[key]->fre++].erase(change);
        freToList[keyToNode[key]->fre].push_front(key);
        keyToNode[key]->iter = freToList[keyToNode[key]->fre].begin();
        if(freToList[minFre].size() == 0)
            minFre++;
        return keyToNode[key]->val;
    }
    
    void put(int key, int value) 
    {
        if(capacity <= 0)
            return;
        if(keyToNode[key] == NULL)
        {
            Node* curr = new Node(value, 1);
            freToList[1].push_front(key);
            curr->iter = freToList[1].begin();
            keyToNode[key] = curr;
            size++;
            if(size > capacity)
            {
                keyToNode.erase(freToList[minFre].back());
                freToList[minFre].pop_back();
                size--;
            }
            minFre = 1;
        }
        else
        {
            get(key);
            keyToNode[key]->val = value;
        }
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,923評論 18 139
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,769評論 0 33
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,765評論 18 399
  • 一、基本數(shù)據(jù)類型 注釋 單行注釋:// 區(qū)域注釋:/* */ 文檔注釋:/** */ 數(shù)值 對于byte類型而言...
    龍貓小爺閱讀 4,288評論 0 16
  • 其一,完全依照出版物,采取現(xiàn)代高科技印刷的手法,以求得同大師真跡的"分毫不差",來達(dá)到迷惑買家出售贗品的目的。這種...
    后來呢_1911閱讀 647評論 0 0