leetcode/include/s0146_lru_cache.hpp
Sainnhe Park bef47e10bf
All checks were successful
ci/woodpecker/push/deploy Pipeline was successful
ci/woodpecker/push/test Pipeline was successful
s0146
2023-03-18 08:42:14 +08:00

51 lines
1.2 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#ifndef S0146_LRU_CACHE_HPP
#define S0146_LRU_CACHE_HPP
#include <cstdlib>
#include <unordered_map>
class LRUCache {
public:
/**
* @brief Least Recently Used Cache
*
* 这是一种常用的页面置换算法,选择最近最久未使用的页面予以淘汰
*
* @param capacity 容量,这是一个正整数
*/
LRUCache(int capacity);
/**
* @brief 读取数据
*
* @param key 数据对应的键值
* @return 数据的值
*/
int get(int key);
/**
* @brief 放入对应的数据
*
* @param key 数据对应的键值
* @param value 数据对应的值
*/
void put(int key, int value);
private:
struct CacheNode {
int key;
int value;
CacheNode *next;
CacheNode *prev;
CacheNode(int key, int value)
: key(key), value(value), next(nullptr), prev(nullptr){};
CacheNode(int key, int value, CacheNode *next, CacheNode *prev)
: key(key), value(value), next(next), prev(prev){};
};
CacheNode *head;
CacheNode *tail;
int capacity;
std::unordered_map<int, CacheNode *> map; // 键值是 key值是该节点的指针
void moveToHead(CacheNode *node); // 将节点移动到头部
};
#endif