0
点赞
收藏
分享

微信扫一扫

C++ LRU O(1)实现


思路 维护双链表 head代表最久没被使用的节点,当我们要更新时 普通链表操作需要遍历,这里我们拿哈希表索引链表的位置,直接o1删除,挺麻烦的。

struct node{
    node* pre;
    node* ne;
    int key;
    int value;
    node(int k,int v){
        key = k;
        value = v;
    }
};

class LRUCache {
public:
    node* head;
    node* tail;
    unordered_map<int ,node*>mp;
    int sz = 0 ;
    LRUCache(int capacity) {
        mp.clear();
        sz = capacity;
        head=new node(0,0);
        tail = new node(0,0);
        head->ne = tail;
        tail->pre = head;
    }
    int get(int key) {
        if(!mp.count(key))  return -1;
        node* tt = new node(key,mp[key]->value);
        node* zz = mp[key];
        node* pp = zz->pre;
        node* dd = zz->ne;
        add(pp,dd);
        node* pt = tail->pre;
        add(pt,tt);
        add(tt,tail);
        mp[key] = tt;
        return mp[key]->value;
    }
    void add(node *a,node *b)
    {
        a->ne = b;
        b->pre = a;
    }
    void put(int key, int value) {
        node *tt = new node(key,value);
        if(!mp.count(key))
        {
            if(mp.size() < sz)
            {
                node *pp = tail->pre;
                add(pp,tt);
                add(tt,tail);
            }
            else{
                // cout << key<<" "<<value<<" "<<mp.size()<<endl;
                node *pp = head->ne;
                node *ppp = pp -> ne;
                mp.erase(pp->key);
                add(head,ppp);
                add(tail->pre , tt);
                add(tt , tail);
            }
        }
        else{
            node* zz = mp[key];
            mp.erase(key);
            node* pp = zz->pre;
            node* dd = zz->ne;
            add(pp,dd);
            node* pt = tail->pre;
            add(pt,tt);
            add(tt,tail);
        }
        mp[key] = tt;
    }
};


举报

相关推荐

0 条评论