LRU和LFU實現


LRU實現

題目鏈接

傳送門

代碼實現

class LRUCache {
public:
    LRUCache(int capacity) : capacity(capacity) {}
    
    int get(int key) {
    	if(mp.find(key) == mp.end()) return -1;
    	put(key, mp[key]->second);//借助put函數來進行更新
    	return mp[key]->second;
    }
    
    void put(int key, int value) {
    	if(mp.find(key) != mp.end()) {
	    	recent.erase(mp[key]);
    	} else if(mp.size() == capacity) {
                mp.erase(recent.back().first);
                recent.pop_back();
    	}
    	recent.push_front(make_pair(key, value));
    	mp[key] = recent.begin();
    }
private:
	int capacity;//LRU的容量
	list<pair<int,int>> recent;//用雙向鏈表來實現LRU的功能,頭為最近使用,尾為最遠使用
	unordered_map<int, list<pair<int,int>>::iterator> mp;//key值對應隊列中的結點
};

LFU實現

題目鏈接

傳送門

代碼實現

class LFUCache {
public:
    LFUCache(int capacity) : capacity(capacity), lst(0) {}
    
    int get(int key) {
    	if(all.count(key) == 0) return -1;
    	put(key, all[key].first);//借助put函數來更新
    	return all[key].first;
    }
    
    void put(int key, int value) {
    	if(capacity == 0) return;
    	if(all.count(key) == 0) {
    		if((int)all.size() >= capacity) {
    			all.erase(fre[lst].back());
    			pos.erase(fre[lst].back());
    			fre[lst].pop_back();
    		}
    		lst = 1;//新增加一個key那么最低頻率肯定是1
    		all[key] = {value, 1};
    		fre[1].push_front(key);
    		pos[key] = fre[1].begin();
    	} else {
    		int cnt = all[key].second;
    		++all[key].second;
    		fre[cnt].erase(pos[key]);
    		fre[cnt+1].push_front(key);
    		pos[key] = fre[cnt+1].begin();
    		all[key].first = value;
    		if(fre[lst].size() == 0) ++lst;
    	}
    }
private:
	int capacity, lst;//LFU的容量、最低頻率
	unordered_map<int, list<int>> fre;//每個頻率存一個鏈表
	unordered_map<int, pair<int,int>> all;//key對應的value和頻率
	unordered_map<int, list<int>::iterator> pos;//key對應的鏈表中的位置
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM