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);
     */
    
  • 相关阅读:
    联网获取图片, 保存用户的图像 bitmap
    使用 线程池,控制线程 , 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待:
    ImageView属性 android:scaleType="fitXY" ,拉伸图片非常好用
    Activity之间传值,Intent
    退出应用程序 按两次退出键
    修炼-------------Android TabHost,TabWidget选项卡总结
    对TabHost、TabWidget的理解分析
    poj 1847 Tram
    hdu 1874 畅通工程续
    hdu 2544 最短路
  • 原文地址:https://www.cnblogs.com/yjcoding/p/13432093.html
Copyright © 2011-2022 走看看