题解 | #设计LRU缓存结构#
设计LRU缓存结构
https://www.nowcoder.com/practice/e3769a5f49894d49b871c09cadd13a61
来一个不考虑效率的版本。
class Solution { public: /** * lru design * @param operators int整型vector<vector<>> the ops * @param k int整型 the k * @return int整型vector */ int set(int key,int val) { for(int i=0;i<count_;i++) { if(v_[i].first==key) { v_[i].second=val; return 0; } } if(count_>=size_) { count_--; v_.erase(v_.begin()); } v_.push_back({key,val}); count_++; return 0; } int get(int key) { for(int i=0;i<count_;i++) { if(v_[i].first==key) { int val1=v_[i].first; int val2=v_[i].second; v_.erase(v_.begin()+i); count_--; set(val1,val2); return val2; } } return -1; } vector<int> LRU(vector<vector<int> >& operators, int k) { // write code here //初始化。 size_=k; count_=0; int n=operators.size(); vector<int> ans; for(int i=0;i<n;i++) { if(operators[i].size()==3) { set(operators[i][1],operators[i][2]); }else { ans.push_back(get(operators[i][1])); } } return ans; } private: int size_; int count_; vector<pair<int,int>> v_; };