146. LRU 快取

lightsong發表於2024-03-08

146. LRU 快取

https://leetcode.cn/problems/lru-cache/description/

思路

https://zhuanlan.zhihu.com/p/85846117

Code

class NODE{
public:
    NODE* prev;
    NODE* next;
    int key;
    int value;

    NODE(int key1, int value1){
        key = key1;
        value = value1;
    }
};


class NODEList{
public:
    NODE* head = NULL;
    NODE* tail = NULL;

    NODEList(){

    }

    void push_front(NODE* one){
        if (head == NULL){
            head = one;
            one->next = NULL;
            
            tail = one;
            one->prev = NULL;
        } else {
            one->next = head;
            head->prev = one;
            head = one;
            head->prev = NULL;
        }
    }

    void push_back(NODE* one){
        if (tail == NULL){
            tail = one;
            one->prev = NULL;

            head = one;
            one->next = NULL;
        } else {
            one->prev = tail;
            tail->next = one;

            tail = one;
            tail->next = NULL;
        }
    }

    void delete_one(NODE* one) {
        if (head == one && tail == one){
            head = NULL;
            tail = NULL;
        } else if (head == one) {
            head = one->next;
            head->prev = NULL;
        } else if (tail == one) {
            tail = one->prev;
            tail->next = NULL;
        } else {
            NODE* prev = one->prev;
            NODE* next = one->next;

            prev->next = next;
            next->prev = prev;
        }
    }
};

class LRUCache {
public:
    int capacity;
    int count;
    map<int, NODE*> query;
    class NODEList nodelist;

    LRUCache(int capacity1) {
        capacity = capacity1;
        count = 0;
    }
    
    int get(int key) {
        // cout << "call get with key=" << key << endl;

        if (!query.contains(key)){
            return -1;
        }

        NODE* one = query[key];
        nodelist.delete_one(one);
        nodelist.push_back(one); 

        return query[key]->value;
    }
    
    void put(int key, int value) {
        // cout << "call put key=" << key << ", value=" << value << endl;

        if (query.contains(key)){
            nodelist.delete_one(query[key]);
            nodelist.push_back(query[key]);

            query[key]->value = value;
            return;
        }

        NODE* one = new NODE(key, value);
        if (count >= capacity){
            NODE* dropped = nodelist.head;
            nodelist.delete_one(nodelist.head);
            nodelist.push_back(one);
            query[key] = one;
            query.erase(dropped->key);
        } else {
            count++;
            nodelist.push_back(one);
            query[key] = one;
        }
    }
};

/**
 * 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);
 */

相關文章