LeetCode: LRU Cache

LeetCode: LRU Cache

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.

地址:https://oj.leetcode.com/problems/lru-cache/

算法:根据题目的意思是让我们模拟LRU算法(最近最常使用算法)。采用一个链表list来表示cache,这样方便删除链表中的任意元素,以及插入头节点元素。另外使用一个map来索引链表中的每一个关键值,这样能够快速的找到链表中关键值相对应的位置。算法实现三个函数:第一个为构造函数,用来设置cache的容量;第二个get函数,用于取得关键值key对应的value值,首先查找cache,如果未找到该key值,返回-1,如果找到该key值,则将该key对应的元素移到链表的头节点,并更新索引值;第三个函数为set函数,用于设置关键值key对应的value值,首先查找cache,如果找到该key值,则设置该key值对应的value值,并把该key值移到链表的头部,并更新索引值,如果没找到且cache容量还未到达最大值,则在链表的头部插入该key值,并且插入该key值对应的索引值,如果没找到且cache容量已经达到最大值,则根据LRU算法原则,删除链表的最后一个节点同时删除其索引值,然后将该key值插入链表头部,并插入索引值。代码:

 1 class LRUCache{
 2 public:
 3     LRUCache(int capacity) {
 4         cap = capacity;
 5     }
 6     
 7     int get(int key) {
 8         map<int,Iter>::iterator it = index_map.find(key);
 9         if(it == index_map.end()){
10             return -1;
11         }
12         Iter p = it->second;
13         int val = it->second->second;
14         cache.push_front(*p);
15         it->second = cache.begin();
16         cache.erase(p);
17         return val;
18     }
19     
20     void set(int key, int value) {
21         map<int,Iter>::iterator it = index_map.find(key);
22         if (it != index_map.end()){
23             cache.push_front(make_pair(key,value));
24             cache.erase(it->second);
25             it->second = cache.begin();
26             return ;
27         }
28         if (cap > cache.size()){
29             cache.push_front(make_pair(key,value));
30             index_map[key] = cache.begin();
31             return ;
32         }
33         index_map.erase(cache.back().first);
34         cache.pop_back();
35         cache.push_front(make_pair(key,value));
36         index_map[key] = cache.begin();
37     }
38     typedef list<pair<int,int> >::iterator Iter;
39     list<pair<int,int> > cache;
40     map<int,Iter> index_map;
41     int cap;
42 };

 

 

posted on 2014-07-28 22:36 Boostable 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/boostable/p/leetcode_lru_cache.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值