算法: 實現LRU緩存,讀取、寫入O(1)實現


這題應該見的不少了,寫寫記錄一下。

實現該功能分析:

(1) O(1) 時間完成查找,那除了 hash 別無選擇。

(2) LRU 最近最少使用算法,為了方便數據的淘汰。需要對最近訪問的數據放未訪問數據之前。

     用雙向鏈表實現即可。(通常情況下,雙向鏈表讀取、插入的時間復雜度都是O(n), 但是如果知道插入位置,則可以實現O(1)實現。)

實現: hash存key對應的數據在雙向鏈表中的位置,就可以完成該功能。

具體代碼:

 1 #include <iostream>
 2 #include <list> //std::list雙向鏈表實現
 3 #include <map>
 4 
 5 const int MAX_VALUE_LEN = 32;
 6 const int MAX_ELEMENT_NUM = 3;
 7 
 8 struct CacheNode{
 9     int key;
10     int len;
11     char data[MAX_VALUE_LEN];
12 };
13 
14 class LRU{
15 public:
16     //默認10個原始
17     LRU(int max_num = MAX_ELEMENT_NUM);
18     ~LRU();
19 
20     //數據獲取
21     bool get(const int key, char *data, int &len);
22 
23     //新增數據
24     bool set(const int key, const char* data, const int len);
25 
26     //打印數據
27     void print_list();
28 private:
29    
30     //更新節點的鏈接
31     //訪問元素后, 需要將元素放置在list 頭部
32     int update_node_link(const int key);
33 
34     int _max_num;
35     std::list<CacheNode*> _list;
36     std::map<int, std::list<CacheNode*>::iterator> _map;
37 };

 


免責聲明!

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



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