Ai
1 Star 0 Fork 0

李璨/leetcode_practice

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
146.lru-缓存.c 2.24 KB
一键复制 编辑 原始数据 按行查看 历史
李璨 提交于 2023-12-17 21:01 +08:00 . feat: 添加文件
/*
* @lc app=leetcode.cn id=146 lang=c
*
* [146] LRU 缓存
*/
// @lc code=start
typedef struct
{
int key;
int val;
UT_hash_handle hh;
} UTTable;
typedef struct
{
UTTable *caches;
int capacity;
} LRUCache;
LRUCache *lRUCacheCreate(int capacity)
{
if (capacity > 3000)
{
return NULL;
}
LRUCache *obj = (LRUCache *)malloc(sizeof(LRUCache));
if (obj == NULL)
{
return NULL;
}
obj->capacity = capacity;
obj->caches = NULL;
return obj;
}
int lRUCacheGet(LRUCache *obj, int key)
{
UTTable *s = NULL;
HASH_FIND_INT(obj->caches, &key, s);
if (s)
{
// 先删除再添加
HASH_DELETE(hh, obj->caches, s);
HASH_ADD_INT(obj->caches, key, s);
}
return s ? s->val : -1;
}
void lRUCachePut(LRUCache *obj, int key, int value)
{
UTTable *current_i = NULL;
UTTable *tmp = NULL;
HASH_FIND_INT(obj->caches, &key, current_i); /* id already in the hash? */
if (current_i)
{
current_i->val = value;
// 先删除再添加
HASH_DELETE(hh, obj->caches, current_i);
HASH_ADD_INT(obj->caches, key, current_i);
return;
}
// prune the cache to MAX_CACHE_SIZE
if (HASH_COUNT(obj->caches) >= obj->capacity)
{
HASH_ITER(hh, obj->caches, current_i, tmp)
{
// prune the first entry (loop is based on insertion order so this deletes the oldest item)
HASH_DELETE(hh, obj->caches, current_i);
free(current_i);
break;
}
}
current_i = malloc(sizeof(*current_i));
current_i->key = key;
current_i->val = value;
HASH_ADD_INT(obj->caches, key, current_i);
}
void lRUCacheFree(LRUCache *obj)
{
UTTable *current_i = NULL;
UTTable *tmp = NULL;
HASH_ITER(hh, obj->caches, current_i, tmp)
{
HASH_DEL(obj->caches, current_i);
free(current_i);
}
free(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);
*/
// @lc code=end
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/Cham_1/leetcode_practice.git
git@gitee.com:Cham_1/leetcode_practice.git
Cham_1
leetcode_practice
leetcode_practice
master

搜索帮助