Created
September 7, 2021 15:08
-
-
Save pidb/520dd4a88aae59c0f18693c7782ce94b to your computer and use it in GitHub Desktop.
Leetcode LRU Cache solution for array [but Time Limit Exceeded]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
struct LRUKV { | |
int key_; | |
int value_; | |
LRUKV(int key, int value) :key_(key), value_(value) {} | |
}; | |
class LRUCache { | |
public: | |
LRUCache(int capacity) | |
:caches_(std::vector<LRUKV>(capacity, LRUKV(-1, -1))){ | |
} | |
int get(int key) { | |
// find | |
for (std::vector<LRUKV>::size_type start = 0, end = caches_.size(); start < end; start++) | |
{ | |
if (caches_[start].key_ == key) { | |
int value = caches_[start].value_; | |
MoveToLast(start); | |
return value; | |
} | |
} | |
return -1; | |
} | |
void put(int key, int value) { | |
// if exists key, only update | |
for (std::vector<LRUKV>::size_type start = 0, end = caches_.size(); start < end; start++) | |
{ | |
if (caches_[start].key_ == key) { | |
caches_[start].value_ = value; | |
// it have access | |
MoveToLast(start); | |
return; | |
} | |
} | |
// if key is not exist, placement it to caches. | |
// for (std::vector<LRUKV>::size_type start = 0, end = caches_.size(); start < end; start++) | |
// { | |
// if (caches_[start].key_ == -1) { | |
// caches_[start].key_ = key; | |
// caches_[start].value_ = value; | |
// return; | |
// } | |
// } | |
// if key is not exist, placement it to caches first. | |
for (std::vector<LRUKV>::size_type start = 0, end = caches_.size() - 1; start < end; start++) | |
{ | |
caches_[start] = caches_[start + 1]; | |
} | |
caches_[caches_.size() - 1] = LRUKV(key, value); | |
} | |
private: | |
void MoveToLast(size_t index) | |
{ | |
LRUKV cache_temp = caches_[index]; | |
for (size_t start = index, end = caches_.size() - 1; start < end; start++) | |
{ | |
caches_[start] = caches_[start + 1]; | |
} | |
caches_[caches_.size() - 1] = cache_temp; | |
} | |
std::vector<LRUKV> caches_; | |
}; | |
/** | |
* Your LRUCache object will be instantiated and called as such: | |
* LRUCache* obj = new LRUCache(capacity); | |
* int param_1 = obj->get(key); | |
* obj->put(key,value); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment