题解 | #设计LRU缓存结构#
设计LRU缓存结构
http://www.nowcoder.com/practice/e3769a5f49894d49b871c09cadd13a61
C++利用队列和vector数组实现,其中队列记录新旧顺序
class Solution { public: /** * lru design * @param operators int整型vector<vector<>> the ops * @param k int整型 the k * @return int整型vector */ vector<int> LRU(vector<vector<int> >& operators, int k) { // write code here vector<vector<int>> n(k,vector<int>(2,0)); queue<int> a; vector<int> p; for (int i=0;i<operators.size();++i) { if (operators[i][0]==1) { if(a.size()<k) { n[a.size()][0]=operators[i][1]; n[a.size()][1]=operators[i][2]; a.push(a.size()); } else { int c=a.front(); a.pop(); a.push(c); n[c][0]=operators[i][1]; n[c][1]=operators[i][2]; } } else { int c2=-1; for (int j=0;j<a.size();++j) { if (n[j][0]==operators[i][1]) { c2=n[j][1]; queue<int> b; while(a.size()) { if(a.front()==j); else b.push(a.front()); a.pop(); } b.push(j); a=b; break; } } p.push_back(c2); } } return p; } };