您的位置:首页 > 其它

Leetcode LRU Cache 解题报告

2014-08-15 07:32 549 查看
这道题我用的是一个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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: