146. LRU Cache

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.

LRU缓存的实现。在这种方法中,如果写入内存的时候容量不足了,最近没用的那一块内存将被换出,以存入新的数据。这里用unordered_map和list来实现。在链表中,最近用过的点在头部,最近没用过的点在尾部,哈希映射表用来保存键值和节点的对应关系。在get函数中,如果在映射表中找不到key对应的那一个节点,返回1;如果找到了,将该节点移到链表的头部(做法是复制和删除原来的点,将复制得到的点插在头部),表示最新用过这个点。在set函数中,如果在映射表中找不到key对应的那一个节点,则要插入该节点,因为是最近用过的,所以查到头部,注意如果链表长度到达最大值,要把最后的节点删除;如果找到了,则更新这个点的实值,然后将该点移到头部(做法和上面的一样)。这样就简单实现了这种缓存机制。


代码:

class LRUCache{
public:
    LRUCache(int capacity):Max(capacity)
	{
    }
    
    int get(int key) 
	{
        auto it=um.find(key);
        if(it==um.end()) return -1;
        auto lit=it->second;
        node newnode(lit->key,lit->val);
        ls.erase(lit);
        ls.push_front(newnode);
        um[key]=ls.begin();
        return ls.begin()->val;
    }
    
    void set(int key, int val) 
	{
		auto it=um.find(key);
        if(it==um.end())
        {
        	if(ls.size()==Max)
        	{
        		um.erase(ls.back().key);
        		ls.pop_back();
			}
			ls.push_front(node(key,val));
			um[key]=ls.begin();
		}
		else
		{
			auto lit=it->second;
			node newnode(key,val);
			ls.erase(lit);
			ls.push_front(newnode);
			um[key]=ls.begin();
		}
    }
    
private:
	struct node
	{
		int key;
		int val;
		node(int k,int v):key(k),val(v){}
	};
	
	list<node>ls;
	unordered_map<int,list<node>::iterator>um;
	int Max;
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值