-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlru_cache.cpp
85 lines (76 loc) · 2.05 KB
/
lru_cache.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// =====================================================================================
//
// Filename: lru_cache.cpp
//
// Description: 146. LRU Cache.
// Design and implement a data structure for Least Recently Used (LRU)
// cache. It should support the following operations: get and put.
//
// Version: 1.0
// Created: 09/09/2019 08:32:57 PM
// Revision: none
// Compiler: g++
//
// Author: Zhu Xianfeng (), [email protected]
// Organization:
//
// =====================================================================================
#include <stdio.h>
#include <list>
#include <unordered_map>
class LRUCache
{
public:
LRUCache(int capacity): capacity_(capacity)
{
}
int get(int key)
{
auto iter = cache_map_.find(key);
if (iter != cache_map_.end())
{
keep(iter);
return iter->second.first;
}
return -1;
}
void put(int key, int value)
{
auto iter = cache_map_.find(key);
if (iter != cache_map_.end())
{
key_list_.erase(iter->second.second);
}
else if (cache_map_.size() == capacity_)
{
cache_map_.erase(key_list_.back());
key_list_.pop_back();
}
key_list_.push_front(key);
cache_map_[key] = std::make_pair(value, key_list_.begin());
}
private:
using LinkedList = std::list<int>;
using CacheValue = std::pair<int, LinkedList::iterator>;
using CacheMap = std::unordered_map<int, CacheValue>;
void keep(CacheMap::iterator iter)
{
key_list_.erase(iter->second.second);
key_list_.push_front(iter->first);
iter->second.second = key_list_.begin();
}
private:
int capacity_;
LinkedList key_list_;
CacheMap cache_map_;
};
int main(int argc, char* argv[])
{
LRUCache cache(2);
cache.put(1, 1);
cache.put(2, 2);
cache.get(1);
cache.put(3, 3);
printf("get(2) -> %d\n", cache.get(2));
return 0;
}