LeetCode OJ LRU Cache
2015-03-23 00:11
239 查看
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:
of the key if the key exists in the cache, otherwise return -1.
key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
getand
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.
class LRUCache{ public: LRUCache(int capacity) { ca = capacity; global_vis = 0; now = 0; cache = new C[capacity]; for (int i = 0; i < capacity; i++) cache[i].vis = -1; // -1 means not visited yet } ~LRUCache() { delete []cache; } int get(int key) { global_vis++; // run time recorder for (int i = 0; i < now; i++) { if (cache[i].k == key && cache[i].vis != -1) { // find the key and it's used(may be there is a right key but not used at all) cache[i].vis = global_vis; return cache[i].v; } } return -1; } void set(int key, int value) { global_vis++; for (int i = 0; i < now; i++) { // search it first, if the key exist, change the value and the visit moment if (cache[i].k == key) { cache[i].v = value; cache[i].vis = global_vis; return; } } if (now == ca) { // if it's full(and the key is not found) int min = cache[0].vis; int pos = 0; for (int i = 0; i < ca; i++) { // find the min visit cache if (min > cache[i].vis) { min = cache[i].vis; pos = i; } } cache[pos].k = key; // change the min visit cache cache[pos].v = value; cache[pos].vis = global_vis; } else { // not full yet(and the key is not found) cache[now].k = key; cache[now].vis = global_vis; cache[now++].v = value; // add a new one } } private: struct C { int vis; // the visit moment, smaller means less recently used int k; int v; }; C *cache; int ca; int now; // the number of the cache right now int global_vis; // a run time counter, help to record the visit moment };
相关文章推荐
- LeetCode146:LRU Cache
- LeetCode LRU Cache STL
- LeetCode LRU Cache 百度笔试
- LeetCode LRU Cache
- [leetcode]LRU Cache @ Python
- 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_Design and implement a data structure for Least Recently Used (LRU) cache
- LeetCode "LRU Cache"
- Leetcode LRU Cache
- LeetCode LRU Cache
- 2015.03.28 leetcode LRU cache 解题记录
- LeetCode LRU Cache
- Leetcode LRU Cache