LC 146. LRU 缓存机制

题目连接点击这里

解决思路

使用哈希表 + 双链表进行存储数据,hash主要负责key -> 链表node 的映射,而node中除了存储key、val其主要作用是判断当前键值的优先级,使用频次越高的键值对放在链表的头起,使用频次低的节点向后放置。详细见代码。

代码

class LRUCache {
public:

    typedef struct Node {
        int key, val;
        Node *left, *right;
        Node(int key, int val) {
            this->key = key;
            this->val = val;
            left = right = nullptr;
        }
    } Node;

    int ca, sz;
    unordered_map<int, Node*> h;
    Node *tail, *head;

    LRUCache(int capacity) {
        ca = capacity;
        sz = 0;
        head = new Node(-1, -1);
        tail = new Node(-1, -1);
        head->right = tail;
        tail->left = head;
    }

    void remove(Node *p) {
        p->left->right = p->right;
        p->right->left = p->left;
    }

    void insert(Node *p) {
        head->right->left = p;
        p->left = head;
        p->right = head->right;
        head->right = p;
    }
    
    int get(int key) {
        if (h.find(key) == h.end()) return -1;
        Node *p = h[key];
        remove(p);
        insert(p);
        return p->val;
    }
    
    void put(int key, int value) {
        if (h.find(key) != h.end()) {
            Node *p = h[key];
            p->val = value;
            remove(p);
            insert(p);
        } else {
            if (sz == ca) {
                Node *p = tail->left;
                remove(p);
                h.erase(p->key);
                sz -- ;
            }
            Node *node = new Node(key, value);
            insert(node);
            h[key] = node;
            sz ++ ;
        }
    }
};

/**
 * 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);
 */
上一篇:b_lc_绝对差值和(贪心)


下一篇:2021-04-01