代码拉取完成,页面将自动刷新
/*
* @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
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。