Leetcode LRU Cache 解题报告

这道题我用的是一个hashmap(unordered_map)记录(key, value)pair,用一个数组(vector)记录key的最近使用顺序。这样能够实现功能,但get和set操作都需要O(n)的时间复杂度,因为需要更新那个数组。看了别人的解法,最好的应该是用一个双向链表记录(key, value)pair,同时用一个hashmap记录每个key在双向链表中的位置,这样O(1)的时间就可以定位,并更新。http://www.programcreek.com/2013/03/leetcode-lru-cache-java/有非常简洁的实现。http://fisherlei.blogspot.com/2013/11/leetcode-lru-cache-solution.html也是。

Java中有个linkedhashmap,里面是按照access order排序的,完全符合这个题目的要求,之前实现过,也能通过测试,具体见http://blog.csdn.net/whuwangyi/article/details/15495845。

暂且这样吧。需要重写。

#include <iostream>
#include <vector>
#include <unordered_map>
#include <cassert>
using namespace std;

class LRUCache{
private:
	unordered_map<int, int> dict;
	int capacity;
	std::vector<int> keys;
public:

	LRUCache(int capacity) {
		this->capacity = capacity;
	}
	
	void updatekey(int key)
	{
		int index = 0;
		while (index != keys.size() && keys[index] != key)
		{
			index++;
		}
		assert(index != keys.size());
		for (int i = index; i + 1 < keys.size(); ++i)
		{
			keys[i] = keys[i + 1];
		}
		keys[keys.size() - 1] = key;
	}

	int get(int key) {
		if (dict.find(key) == dict.end())
		{
			return -1;
		}
		int value = dict[key];
		updatekey(key);
		return value;
	}

	void set(int key, int value) {
		if (dict.find(key) == dict.end())
		{
			if (keys.size() == capacity)
			{
				dict.erase(keys[0]);
				for (int i = 0; i + 1 < keys.size(); ++i)
				{
					keys[i] = keys[i + 1];
				}
				keys.pop_back();
			}
			dict[key] = value;
			keys.push_back(key);
		}
		else
		{
			updatekey(key);
			dict[key] = value;
		}
	}
};

int main()
{
	LRUCache lru(2);
	lru.set(1, 1);
	lru.set(2, 2);
	// cout<<lru.get(1)<<endl;
	lru.set(3, 3);
	// cout<<lru.get(1)<<endl;
	// cout<<lru.get(2)<<endl;
	// cout<<lru.get(3)<<endl;
	lru.set(4, 4);
	cout<<lru.get(1)<<endl;
	cout<<lru.get(2)<<endl;
	cout<<lru.get(3)<<endl;
	cout<<lru.get(4)<<endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值