Redian新闻
>
C++高手看下这个LC的LRU Cache的实现
avatar
C++高手看下这个LC的LRU Cache的实现# JobHunting - 待字闺中
r*7
1
可以pass所有的test cases,不知道是不是显得比较初级,本人C++比较普通,谢谢指
教!
class LRUCache{
public:
typedef map::iterator> > KVType;
LRUCache(int capacity) {
mCapacity = capacity;
}

int get(int key) {
KVType::iterator it = mKeyValuePair.find(key);
if (it == mKeyValuePair.end()) {
return -1;
}
int result = it->second.first;
list::iterator keysIt = it->second.second;
mKeys.erase(keysIt);
mKeys.push_front(key);
mKeyValuePair[key] = make_pair(result, mKeys.begin());
return result;
}

void set(int key, int value) {
int result = get(key);
// already exists
if (result != -1) {
mKeyValuePair[key].first = value;
return;
}
// doesn't exists and not full
if (mKeys.size() != mCapacity) {
mKeys.push_front(key);
mKeyValuePair[key] = make_pair(value, mKeys.begin());
return;
}
// doesn't exists and full
mKeyValuePair.erase(mKeys.back());
mKeys.pop_back();
mKeys.push_front(key);
mKeyValuePair[key] = make_pair(value, mKeys.begin());
}
private:
list mKeys;
KVType mKeyValuePair;
int mCapacity;
};
avatar
a*u
2
请问你的mKeys,pop_back()和push_front()的时间复杂度多少?如果不是O(1), 可以
考虑换成double linkedlist
avatar
a*u
3
查了下,list的操作时间的确是O(1), 那整体设计没啥大问题。至于语言让懂c++的人
看吧
avatar
r*7
4
算法应该没啥问题,这个题也没啥算法吧,所以想让高手看看C++怎么写比较
sophisticated

【在 a*****u 的大作中提到】
: 查了下,list的操作时间的确是O(1), 那整体设计没啥大问题。至于语言让懂c++的人
: 看吧

avatar
e*i
5
looks good! my 2cents in comments:
class LRUCache{ // maybe it's better to be templated key instead of 'int'?
public:
typedef map::iterator> > KVType; // map O(lgn)
vs unordered_map O(n) ??
LRUCache(int capacity) {
mCapacity = capacity;
}

int get(int key) {
KVType::iterator it = mKeyValuePair.find(key); //auto it = ...
if (it == mKeyValuePair.end()) {
return -1;
}
int result = it->second.first;
mKeys.erase(it->second.second); // keysIt used only once, combine
the line above
mKeys.push_front(key);
mKeyValuePair[key] = make_pair(result, mKeys.begin());
return result;
}

void set(int key, int value) {
int result = get(key); //to optimise, maybe copy the first 3 lines
in get() instead of calling get()
// since you're putting the kv on top (push_front) anyway later here.
// already exists
if (result != -1) {
mKeyValuePair[key].first = value;
return;
}
if (mKeys.size() == mCapacity) {
// doesn't exists and full
mKeyValuePair.erase(mKeys.back());
mKeys.pop_back();
}
// doesn't exists and not full
mKeys.push_front(key);
mKeyValuePair[key] = make_pair(value, mKeys.begin());
}
private:
list mKeys;
KVType mKeyValuePair;
int mCapacity; // make it const, and init with ctor; and, unsigned int
};

【在 r****7 的大作中提到】
: 可以pass所有的test cases,不知道是不是显得比较初级,本人C++比较普通,谢谢指
: 教!
: class LRUCache{
: public:
: typedef map::iterator> > KVType;
: LRUCache(int capacity) {
: mCapacity = capacity;
: }
:
: int get(int key) {

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。