[LeetCode] 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.

题解:

设计一个最近最少使用的数据结构。算法不难,插入一个(key, value),如果capacity是满的,那就把最久未操作的元素删除,这个(key,value)再插进去。代码时参考别人的,list数据结构没有用过,对STL还是不熟。

#include <list>
#include <unordered_map>
using namespace std;
struct CacheNode
{
	int key;
	int value;
	CacheNode(int k, int v): key(k), value(v){}
};

class LRUCache
{
public:
	LRUCache(int capacity){
		size = capacity;
	}
	
	int get(int key){
		if (cacheMap.find(key) != cacheMap.end())
		{
			auto it = cacheMap[key];
			cacheList.splice(cacheList.begin(), cacheList, it);
			cacheMap[key] = cacheList.begin();
			return cacheList.begin()->value;
		}
		else
			return -1;
	}
	void set(int key, int value){
		if (cacheMap.find(key) == cacheMap.end())
		{
			if (cacheList.size() == size)
			{
				// 消除对应元素
				cacheMap.erase(cacheList.back().key);
				cacheList.pop_back();
			}
			cacheList.push_front(CacheNode(key,value));
			cacheMap[key] = cacheList.begin();
		}
		else
		{
			auto it =cacheMap[key];
			cacheList.splice(cacheList.begin(),cacheList,it);
			cacheMap[key] = cacheList.begin();
			cacheList.begin()->value = value;
		}
	}
	

private:
	int size;
	list<CacheNode> cacheList;
	unordered_map<int, list<CacheNode>::iterator > cacheMap;
};


注,一些语法知识:

auto:c++11 增加的一个变量,自动类型推断,如:auto i = 4; 自动推断i为int类型

splice(): list容器中的拼接操作,有三种重载函数:

	void splice (iterator position, list& x);
	void splice (iterator position, list& x, iterator i);
	void splice (iterator position, list& x, iterator first, iterator last); 
	第一种是,把x中的全部元素插入到list中position之前的位置,同时把x中的所有元素都删除,x和list的大小都发生改变
	第二种是,把x中i指向的那个元素插入到list中的position之前的位置,同时把x中的i指向的那个元素删除,x和list的大小都发生改变
	第三种和第二种类似,变成范围似的删除.

void advance(InputIterator& it, Distance n)

移动到离迭代器it距离为n的元素,从0开始计数,例如:


             for(int i =0; i<10; i++)
                    mylist.pushback(i);
             list<int>::iteraotr it = mylist.begin();
             advace(it, 5);
             cout<<*it<<endl;
最后输出的元素为5;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值