zoukankan      html  css  js  c++  java
  • #146 LRU cache

    class LRUCache {
    private:
    	std::unordered_map<int, int> mapData;
    	std::unordered_map<int, std::list<int>::iterator> mapIndex;
    	std::list<int> list;
    	int maxSize;
    public:
    	LRUCache(int capacity) {
    		maxSize = capacity;
    	}
    
    	int get(int key) {
    		auto search = mapData.find(key);
    
    		if (search != mapData.end()) {//find it
    			auto pair_delete = mapIndex.find(key);
    			list.erase(pair_delete->second);
    
                list.push_back(key);			
                pair_delete->second = std::prev(list.end());
    			return search->second;
    		}
    		else {//not find
    			return -1;
    		}
    	}
    
    	void put(int key, int value) {
    		auto search = mapData.find(key);
    		if (search != mapData.end()) {//find it
    			auto pair_delete = mapIndex.find(key);
    			list.erase(pair_delete->second);
    
                list.push_back(key);
                pair_delete->second = std::prev(list.end());	
    			search->second = value;
    
    		}
    		else {//not find
    			  //push to list
    			list.push_back(key);
    			mapData[key] = value;
    			mapIndex[key] = std::prev(list.end());
    
    			//overflow
    			this->removeLRU();
    		}
    	}
    	void removeLRU() {
    		if (list.size() > maxSize) {
    			auto iterBegin = list.begin();
    			mapData.erase(*iterBegin);
    			mapIndex.erase(*iterBegin);
    			list.pop_front();
    		}
    
    	}
    };
    

      

  • 相关阅读:
    springboot整合springmvc原理
    springboot Thymeleaf
    springboot 首页处理
    springboot整合Druid
    springboot 整合JDBC
    CentOS安装Mysql
    springboot 多环境切换
    springboot JSR303数据校验
    【转载】WEB架构师成长之路
    一些想法
  • 原文地址:https://www.cnblogs.com/dongfangchun/p/7724736.html
Copyright © 2011-2022 走看看