-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLRUCache.h
75 lines (65 loc) · 1.74 KB
/
LRUCache.h
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
//
// LRUCache.h
//
//
// https://leetcode.com/problems/lru-cache/description/
//
#ifndef LRUCache_h
#define LRUCache_h
class LRUCache {
public:
unordered_map<int, int> cache;
vector<int> usedTimes;
int capacity;
int numOfCurrentElements;
LRUCache(int capacity) : capacity(capacity), numOfCurrentElements(0) {
}
int get(int key) {
if (cache.find(key) == cache.end())
{
return -1;
}
int value = cache[key];
for (int i = 0; i < usedTimes.size(); i++)
{
if (usedTimes[i] == key)
{
usedTimes.erase(usedTimes.begin() + i);
usedTimes.insert(usedTimes.begin(), key);
}
}
return value;
}
void put(int key, int value) {
if (cache.find(key) != cache.end())
{
cache[key] = value;
for (int i = 0; i < usedTimes.size(); i++)
{
if (usedTimes[i] == key)
{
usedTimes.erase(usedTimes.begin() + i);
usedTimes.insert(usedTimes.begin(), key);
}
}
return;
}
numOfCurrentElements++;
if (numOfCurrentElements > capacity)
{
int mapKey = usedTimes[usedTimes.size() - 1];
usedTimes.pop_back();
numOfCurrentElements--;
cache.erase(mapKey);
}
usedTimes.insert(usedTimes.begin(), key);
cache[key] = value;
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/
#endif /* LRUCache_h */