zoukankan      html  css  js  c++  java
  • 146. 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
    
    
    

    解析

    • list<pair<int,int>> 是一个双向链表,存储键值(key,value),map<int,list<pair<int,int>>::iterator>>是用来存放key值所对应的list中的位置;

    • list链表的开头,是最近使用过的,当每次进行get()和put()操作时,我们就要更新。要注意的是,若(key1,value1)已经存在,当put(key1,value2)时,我们要直接修改value值,同时放到链表的开头。list链表的末尾,是最久使用过的,当容量满时,就要将它替换出去,将最新的(key,value)放在链表开头

    
    class LRUCache {
    public:
    	// 定义数据结构
    	int n;
    	list<pair<int, int>> lis; //链表头为最新访问的,链表尾为最近最少访问的
    	map<int, list<pair<int, int>>::iterator> mp; //记录每个关键字在list中的位置
    
    	LRUCache(int capacity) {
    		n = capacity;
    	}
    
    	int get(int key) {
    
    		int ret = -1;
    		if (mp.find(key) != mp.end())  //已经存在;更新cache顺序就行
    		{
    			auto iter = mp[key];
    			ret = iter->second; //记录查询key的value
    
    			lis.erase(iter);
    			lis.push_front(make_pair(key, ret));
    
    			mp[key] = lis.begin();
    
    		}
    		return ret;
    	}
    
    	void put(int key, int value) {
    
    		auto iter = mp.find(key); //iter是mp的迭代器
    
    		if (iter != mp.end()) //已经存在,更新list位置
    		{
    			lis.erase(iter->second);
    		}
    		else if (lis.size() < n)
    		{
    
    		}
    		else //list里面没有key,且list已经满了
    		{
    			//auto it = lis.end(); //end()迭代器指向最后元素的后面位置
    			//it--;
    			//m.erase(it->first);
    			//lis.erase(it);
    
    			int key = lis.back().first; //这样操作避免使用迭代器失效问题出现
    			lis.pop_back();
    			mp.erase(key);
    		}
    
    		lis.push_front(make_pair(key, value));
    		mp[key] = lis.begin();
    	}
    };
    

    题目来源

  • 相关阅读:
    二十八 .Django中模型类中Meta元对象了解
    【POJ2376】Cleaning Shifts
    【CF600E】Lomsat gelral
    【hiho1035】自驾旅行III
    【模板】manachar
    【hiho1065】全图传送
    【洛谷P1450】硬币购物
    【HDU2204】Eddy's爱好
    【CF208E】Blood Cousins
    【CF451E】Devu and Flowers
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/9597451.html
Copyright © 2011-2022 走看看