zoukankan      html  css  js  c++  java
  • leetcode146 LRU缓存机制(Medium)

    题目来源:leetcode146 LRU缓存机制

    题目描述:

    运用你所掌握的数据结构,设计和实现一个  LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。

    获取数据 get(key) - 如果关键字 (key) 存在于缓存中,则获取关键字的值(总是正数),否则返回 -1。
    写入数据 put(key, value) - 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字/值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。

    进阶:

    你是否可以在 O(1) 时间复杂度内完成这两种操作?

    示例:

    LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );

    cache.put(1, 1);
    cache.put(2, 2);
    cache.get(1); // 返回 1
    cache.put(3, 3); // 该操作会使得关键字 2 作废
    cache.get(2); // 返回 -1 (未找到)
    cache.put(4, 4); // 该操作会使得关键字 1 作废
    cache.get(1); // 返回 -1 (未找到)
    cache.get(3); // 返回 3
    cache.get(4); // 返回 4

    解题思路:

    class LRUCache {
    public:
        LRUCache(int capacity) {
            cat=capacity;
        }
        
        int get(int key) {
            auto it=hash.find(key);
            int ans=-1;//没找到返回-1
            if(it!=hash.end()){
                ans=it->second->second;//得到key对应的value值
                data.erase(it->second);//删除原来结点
                data.push_front(make_pair(key,ans));//移动到链表的头部
                it->second=data.begin();//hash位置更新为链表的头部
            }
            return ans;
        }
        
        void put(int key, int value) {
            auto it=hash.find(key);
            if(it!=hash.end())
            {
                data.erase(it->second);//如果要找的值已经存在,删除原来位置,移动到首部
                data.push_front(make_pair(key,value));//移动到链表最前面
                hash[key]=data.begin();//更新位置为链表首部
            }
            else if(hash.size()<cat){
                data.push_front(make_pair(key,value));//在链表最前面放置结点
                hash[key]=data.begin();//更新位置为链表首部
            }
            else{
                auto it1=data.end();
                it1--;
                hash.erase(it1->first);//删掉对应的hash
                data.erase(it1);//删掉末尾最不常使用的结点
                data.push_front(make_pair(key,value));//在链表最前面放置结点
                hash[key]=data.begin();
            }
    
        }
    private:
        int cat;
        list<pair<int,int>> data;//双向链表
        map<int,list<pair<int,int>>::iterator> hash;//key值和在双向链表中的位置
    };
    
    /**
     * 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);
     */
    
  • 相关阅读:
    【MFC】在CHtmlView中在同一窗口显示新打开页面
    【MFC】CHtmlView::GetSource中文乱码的问题
    【Win32】对指定进程进行禁音
    【MFC】在CHtmlView中准确判断页面加载完成
    【MFC】CHtmlView或WebBrowser禁止脚本错误提示
    【MFC】CDialogBar中按钮不可用
    【转载记录】Accessing Device Drivers from C#
    【源代码R3】移植一份LARGE_INTEGER转时间的代码
    Square Root of Permutation
    MySQL创建视图命令
  • 原文地址:https://www.cnblogs.com/yjcoding/p/13432093.html
Copyright © 2011-2022 走看看