Scribbling

[C++] LRU Cache 본문

Computer Science/C++

[C++] LRU Cache

focalpoint 2024. 10. 5. 13:31

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