首页 > 其他 > 详细

Leetcode个人总结11 LRU cache设计(1)

时间:2014-03-28 20:05:54      阅读:431      评论:0      收藏:0      [点我收藏+]

1. 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.

bubuko.com,布布扣
 1 class LRUCache{
 2 public:
 3     LRUCache(int capacity) {
 4         max_capacity = capacity;
 5         cur_size = 0;
 6     }
 7     
 8     int get(int key) {
 9         int value;
10         if (hash.find(key) == hash.end()) {
11             return -1;
12         }
13         else {
14             auto it = hash[key];
15             value = it->second;
16             cache.push_front(*it);
17             cache.erase(it); // delete
18             
19             hash[key] = cache.begin();
20         }
21         return value;
22     }
23     
24     void set(int key, int value) {
25            
26         if (hash.find(key) != hash.end()) {
27             cache.erase(hash[key]);
28             hash.erase(key);        
29         }
30         else {
31             if (cur_size < max_capacity) {
32                 cur_size++;
33             }
34             else {
35                 // delete old (key,value)
36                 list<pair<int,int> >::iterator it = cache.begin();
37                 advance(it, cur_size-1);
38                 hash.erase(it->first);
39                 cache.erase(it);
40             }
41         }
42             
43         cache.push_front(pair<int,int>(key,value));
44         hash[key] = cache.begin();
45     }
46 

47 private:
48     int max_capacity;
49     int cur_size;
50     list<pair<int,int> > cache;
51     unordered_map<int, list<pair<int,int> >::iterator> hash;
52 };
bubuko.com,布布扣

Leetcode个人总结11 LRU cache设计(1),布布扣,bubuko.com

Leetcode个人总结11 LRU cache设计(1)

原文:http://www.cnblogs.com/zhengjiankang/p/3629848.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!