zoukankan      html  css  js  c++  java
  • [LeetCode] LRU Cache [Forward]

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

    get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
    set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

    struct node {
        node* pre;
        int key;
        int value;
        node* next;
        node(int k, int v):key(k),value(v),pre(NULL),next(NULL) {};
    };
    
    class LRUCache {
        map<int, node*> mp;
        node* head;
        node* tail;
        int size;
        int capacity;
    public:
        LRUCache(int c) {
            if (c < 1)return;
            head = new node(0, 0);
            tail = new node(0, 0);
            head->next = tail;
            tail->pre = head;
            mp.clear();
            size = 0;
            capacity = c;
        }
    
        int get(int k) {
            map<int, node*>::iterator it = mp.find(k);
            if (it != mp.end()) {
                node* cur = (*it).second;
                cur->pre->next = cur->next;
                cur->next->pre = cur->pre;
                putToHead(cur);
                return cur->value;
            } else
                return -1;
        }
    
        void set(int k, int val) {
            if (capacity < 1)return;
            map<int, node*>::iterator it = mp.find(k);
            if (it != mp.end()) {//find
                node* cur = (*it).second;
                cur->pre->next = cur->next;
                cur->next->pre = cur->pre;
                cur->value = val;
                putToHead(cur);
            } else {//not find
                node* tmp = new node(k,val);
                putToHead(tmp);
                mp[k] = tmp;
                if (size < capacity) {//size < capacity
                    size++;
                } else {//size >= capacity
                    node* deltmp = tail->pre;
                    tail->pre = deltmp->pre;
                    deltmp->pre->next = tail;
                    it = mp.find(deltmp->key);
                    mp.erase(it);
                    delete deltmp;
                }
            }
        }
        void putToHead(node* cur)
        {
            cur->next = head->next;
            cur->pre = head;
            cur->next->pre = cur;
            head->next = cur;
        }
    
    };
  • 相关阅读:
    SQL Union和SQL Union All用法
    background:url() 背景图不显示
    媒体查询_网页打印样式
    提示让IE8以下版本的浏览器去更新浏览器
    python_继承supper错误
    Django_xadmin_应用外键搜索功能错误
    Django_404_403_500页面处理
    Django_中国化
    Django_上传图片和模版获取图片
    Django_生产环境静态文件配置
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3673956.html
Copyright © 2011-2022 走看看