學渣帶你刷Leetcode146 LRU快取機制

2021-10-23 07:10:28 字數 2691 閱讀 7801

運用你所掌握的資料結構,設計和實現乙個  lru (最近最少使用) 快取機制。它應該支援以下操作: 獲取資料 get 和 寫入資料 put 。

獲取資料 get(key) - 如果金鑰 (key) 存在於快取中,則獲取金鑰的值(總是正數),否則返回 -1。

寫入資料 put(key, value) - 如果金鑰已經存在,則變更其資料值;如果金鑰不存在,則插入該組「金鑰/資料值」。當快取容量達到上限時,它應該在寫入新資料之前刪除最久未使用的資料值,從而為新的資料值留出空間。

高階:你是否可以在 o(1) 時間複雜度內完成這兩種操作?

示例:lrucache cache = new lrucache( 2 /* 快取容量 */ );

cache.put(1, 1);

cache.put(2, 2);

cache.get(1);       // 返回  1

cache.put(3, 3);    // 該操作會使得金鑰 2 作廢

cache.get(2);       // 返回 -1 (未找到)

cache.put(4, 4);    // 該操作會使得金鑰 1 作廢

cache.get(1);       // 返回 -1 (未找到)

cache.get(3);       // 返回  3

cache.get(4);       // 返回  4

詳細解釋關注 b站  【c語言全**】學渣帶你刷leetcode 不走丟 

#define nothingness -1

struct node;//雙向鍊錶

struct hash;//雜湊表結構

typedef struct lrucache;

struct hash* hashmap(struct hash* table, int key, int capacity)

void headinsertion(struct node* head, struct node* cur)

else

}}lrucache* lrucachecreate(int capacity) */

lrucache* obj = (lrucache*)malloc(sizeof(lrucache));

obj->table = (struct hash*)malloc(capacity * sizeof(struct hash));

memset(obj->table, 0, capacity * sizeof(struct hash));

obj->head = (struct node*)malloc(sizeof(struct node));

obj->tail = (struct node*)malloc(sizeof(struct node));

//建立頭、尾結點並初始化

obj->head->prev = null;

obj->head->next = obj->tail;

obj->tail->prev = obj->head;

obj->tail->next = null;

//初始化快取 大小 和 容量

obj->size = 0;

obj->capacity = capacity;

return obj;

}int lrucacheget(lrucache* obj, int key)

while ( addr->next != null && addr->unused->key != key)

if (addr->unused->key == key)

return nothingness;

}void lrucacheput(lrucache* obj, int key, int value)

ptr->next = remove->next;//在 table[last->key % capacity] 鍊錶中刪除結點

remove->next = null;

remove->unused = null;//解除對映

free(remove);//**資源

struct hash* new_node = (struct hash*)malloc(sizeof(struct hash));

new_node->next = addr->next;//連線到 table[key % capacity] 的鍊錶中

addr->next = new_node;

new_node->unused = last;//最大化利用雙鏈表中的結點,對其重對映(節約空間)

last->key = key;//重新賦值

last->value = value;

headinsertion(obj->head, last);//更新最近使用的資料

}else

}else

}void lrucachefree(lrucache* obj)

/** * your lrucache struct will be instantiated and called as such:

* lrucache* obj = lrucachecreate(capacity);

* int param_1 = lrucacheget(obj, key);

* lrucacheput(obj, key, value);

* lrucachefree(obj);

*/

學渣帶你刷Leetcode0035搜尋插入位置

給定乙個排序陣列和乙個目標值,在陣列中找到目標值,並返回其索引。如果目標值不存在於陣列中,返回它將會被按順序插入的位置。你可以假設陣列中無重複元素。示例 1 輸入 1,3,5,6 5 輸出 2 示例 2 輸入 1,3,5,6 2 輸出 1 示例 3 輸入 1,3,5,6 7 輸出 4 示例 4 輸入...

學渣帶你刷Leetcode0063不同路徑 II

乙個機械人位於乙個 m x n 網格的左上角 起始點在下圖中標記為 start 機械人每次只能向下或者向右移動一步。機械人試圖達到網格的右下角 在下圖中標記為 finish 現在考慮網格中有障礙物。那麼從左上角到右下角將會有多少條不同的路徑?網格中的障礙物和空位置分別用 1 和 0 來表示。說明 m...

學渣帶你刷Leetcode0066加一

給定乙個由整數組成的非空陣列所表示的非負整數,在該數的基礎上加一。最高位數字存放在陣列的首位,陣列中每個元素只儲存單個數字。你可以假設除了整數 0 之外,這個整數不會以零開頭。示例 1 輸入 1,2,3 輸出 1,2,4 解釋 輸入陣列表示數字 123。示例 2 輸入 4,3,2,1 輸出 4,3,...