标签:
class LRUCache{ public: //map<int,int> v; vector<int> v; map<int,int> m; int s; LRUCache(int capacity) { s=capacity; } void adjust(int key){ int idx = -1; //for(int i = 0; i <= v.size() - 1; i ++) for(int i = v.size()-1; i >=0; i --) //必须是倒序的,正序的不可以 if(v[i] == key){ idx = i; break; } v.erase(v.begin() + idx); v.push_back(key); /*std::vector<int>::iterator it = v.end(); while(it!=v.begin()){ it--; if(*it == key) {v.erase(it); v.push_back(key); break;} }*/ } int get(int key) { /*if(!m.count(key)) return -1;*/ //艾玛这个起了解决超时问题的决定性作用 if(m.find(key) == m.end()){ return -1; } else{ /*std::vector<int>::iterator it = v.begin(); while(it<v.end()){ if(*it == key) { v.erase(it); break;} it++; } v.push_back(key);*/ adjust(key); return m[key]; //v.insert(pair<int,int>(key,v.size())); } } void set(int key, int value) { if(m.count(key)) { //如果更新改key的值 m[key] = value; /*std::vector<int>::iterator it = v.begin(); while(it<v.end()){ if(*it == key) { v.erase(it); break;} it++; } v.push_back(key);*/ adjust(key); return; } else if(v.size() < s){ //插入新值,并且队列未满 m[key] = value; v.push_back(key); return; } else {//插入新值,并且队列已满 // m.insert(pair<int,int>(key,value)); m.erase(v[0]); //这里可以直接用元素来删除,不一定非要用iterator m[key] = value; v.erase(v.begin()); v.push_back(key); return; } } };
标签:
原文地址:http://www.cnblogs.com/julie-yang/p/4676829.html