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;
};
教!
class LRUCache{
public:
typedef map
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
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
KVType mKeyValuePair;
int mCapacity;
};