题解 | #设计LRU缓存结构#
设计LRU缓存结构
http://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 find(queue<pair<int,int>>q,int num) { int size = q.size(); for(int i = 0;i < size;i ++) { auto a = q.front(); if(a.first == num) { return a.second; } q.pop(); } return -1; } void sort(queue<pair<int,int>> &q,int key) { queue<pair<int,int>> temp; int size = q.size(); pair<int,int> te; for(int i = 0;i < size;i ++) { auto a = q.front(); if(a.first == key) { te = a; } else { temp.push(a); } q.pop(); } temp.push(te); // int i = 0; while(temp.size()) { te = temp.front(); temp.pop(); q.push(te); // cout << i << te.first << te.second << endl; // i ++; } } vector<int> LRU(vector<vector<int> >& operators, int k) { // write code here vector<int> result; queue<pair<int,int>> q; int size = operators.size(); for(int i = 0;i < size;i ++) { if(operators[i][0] == 1)//set { if(q.size() == k) { q.pop();//出队 } q.push({operators[i][1],operators[i][2]}); } else if(operators[i][0] == 2)//get { int temp_num = find(q,operators[i][1]); result.push_back(temp_num); if(temp_num == -1) { continue; } } sort(q,operators[i][1]); } return result; } };