leetcode:LRU Cache
来源:互联网 发布:python爬虫工程师 编辑:程序博客网 时间:2024/05/17 05:06
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and set
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value)
- Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
LRU缓存算法实现,这个算法就是在缓存已满时,将最久未使用的元素移出缓存。
经典实现就是双向链表加哈希,每次使用(get or set)都使用哈希值找到这个元素在双链表中的位置,然后将它移到最前面,如果缓存已满就删除队尾的元素。哈希中放的是元素的地址,在新增、移动和删除元素的时候都要在Hash表中作对应修改,而双向链表主要是为了方便删除。
class Node{public: int key, val; Node *pre, *next; Node(int k, int v): key(k), val(v), pre(NULL), next(NULL) {}};class LRUCache{ map<int, Node*> mp; map<int, Node*>::iterator iter; int used, cap; Node *head, *tail;public: LRUCache(int capacity) { mp.clear(); used = 0, cap = capacity; head = new Node(0, 0); tail = new Node(0, 0); head->next = tail, tail->pre = head; } ~LRUCache(){ for (Node *n = head, *nnext; n; n = nnext) { nnext = n->next; delete n; } } int get(int key) { if ((iter = mp.find(key)) != mp.end()) { movetoFirst(iter->second); return iter->second->val; }else return -1; } void set(int key, int value) { if ((iter = mp.find(key)) != mp.end()) { iter->second->val = value; movetoFirst(iter->second); } else { Node *node; if (used == cap) { mp.erase(tail->pre->key); node = tail->pre; node->key = key, node->val = value; } else { node = new Node(key, value); used++; } mp[node->key] = node; movetoFirst(node); } } void movetoFirst(Node *node) { if (node->pre && node->next) { node->pre->next = node->next; node->next->pre = node->pre; } node->pre = head, node->next = head->next; head->next->pre = node, head->next = node; }};
1 0
- LeetCode LRU 缓存 LRU Cache
- LRU Cache | leetcode
- Leetcode: LRU Cache
- LeetCode:LRU Cache
- Leetcode: LRU Cache
- [LeetCode] LRU Cache
- leetcode之LRU Cache
- [LeetCode]LRU Cache
- [LeetCode] LRU Cache
- leetcode LRU Cache
- LeetCode题解:LRU Cache
- LeetCode | LRU Cache
- Leetcode: LRU Cache
- [LeetCode] LRU Cache
- LeetCode OJ:LRU Cache
- Leetcode LRU Cache
- LeetCode - LRU Cache
- [Leetcode] LRU Cache (Java)
- C++中四种强制类型转换
- (续)上次周赛两道题【kmp,bfs】
- 暑假读书
- 454 Authentication failed, please open smtp flag first!
- Hibernate学习之Transient、Persistent、Detached三种状态
- leetcode:LRU Cache
- NOIP2009 Hankson的趣味题
- PHP日志
- 【笔试】12、企业发放的奖金根据利润提成。
- 《算法导论》读书笔记
- Jump Game II
- 标准模板库(STL)使用入门(上)
- hdoj 1513 Palindrome 【LCS】
- MySQL limit用法,分页的实现。