일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Class
- Substring with Concatenation of All Words
- 315. Count of Smaller Numbers After Self
- data science
- iterator
- 30. Substring with Concatenation of All Words
- Python
- 시바견
- 밴픽
- 운영체제
- LeetCode
- 컴퓨터의 구조
- kaggle
- 43. Multiply Strings
- shiba
- DWG
- 파이썬
- concurrency
- Python Code
- Python Implementation
- Convert Sorted List to Binary Search Tree
- Protocol
- attribute
- Generator
- Decorator
- 715. Range Module
- 109. Convert Sorted List to Binary Search Tree
- t1
- Regular Expression
- 프로그래머스
Archives
- Today
- Total
Scribbling
[C++] LRU Cache 본문
https://leetcode.com/problems/lru-cache/description/
#include <iostream>
#include <list>
#include <map>
using namespace std;
class Node {
public:
int key;
int val;
Node() {}
Node(int key=-1, int val=-1) : key(key), val(val) {}
~Node() {}
};
class LRUCache {
public:
list<Node> ll;
map<int,list<Node>::iterator> dict;
int capacity;
int cnt;
LRUCache(int capacity) : capacity(capacity), cnt(0) {}
int get(int key) {
if (dict.find(key) != dict.end()) {
auto it = dict[key];
Node node(*it);
ll.erase(it);
ll.push_back(node);
dict[key] = prev(ll.end());
return node.val;
}
else {
return -1;
}
}
void put(int key, int value) {
if (dict.find(key) != dict.end()) {
auto it = dict[key];
Node node = Node(*it);
node.val = value;
ll.erase(it);
ll.push_back(node);
dict[key] = prev(ll.end());
}
else {
if (cnt == capacity) {
Node popped = ll.front();
dict.erase(popped.key);
ll.pop_front();
Node node = Node(key, value);
ll.push_back(node);
dict[key] = prev(ll.end());
}
else {
Node node = Node(key, value);
ll.push_back(node);
dict[key] = prev(ll.end());
cnt++;
}
}
}
};
int main() {
LRUCache lru(2);
lru.put(2, 1);
lru.put(1, 1);
lru.get(2);
}
'Computer Science > C++' 카테고리의 다른 글
[C++] Interface (0) | 2024.10.02 |
---|---|
[C++] Object Oriented Programming (0) | 2024.10.01 |
[C++] Strings (0) | 2024.09.30 |
[C++] Abstract Class, Polymorphism (0) | 2024.09.28 |
[C++] Virtual Functions (0) | 2024.09.28 |