双链表模拟队列,然后两个map存储key-value和key-ListNode优化查找时间。
struct ListNodel { int key; ListNodel *before; ListNodel *next; ListNodel(int x) : key(x),before(NULL),next(NULL) {} }; class LRUCache{ public: map<int,int>mapkv; map<int,ListNodel</em>>mapkl; int capacityq; ListNodel * head,*tail; LRUCache(int capacity) { capacityq = capacity; mapkv.clear(); mapkl.clear(); head = NULL; tail = NULL; }</p> <pre><code>int get(int key) { map&lt;int,int&gt;::iterator it = mapkv.find(key); if(it != mapkv.end()) { update(key); return it-&gt;second; } else { return -1; } } void set(int key, int value) { map&lt;int,int&gt;::iterator it = mapkv.find(key); if(it != mapkv.end()) { it-&gt;second = value; update(key); } else { if(mapkv.size() &lt; capacityq) { insertKeyValue(key,value); } else { ListNodel * tmp = head; head = head-&gt;next; mapkl.erase(tmp-&gt;key); mapkv.erase(tmp-&gt;key); delete(tmp); insertKeyValue(key,value); } } } </code></pre> <p>private: void insertKeyValue(int key,int value) { mapkv.insert(map<int,int>::value_type(key,value)); if(head == NULL) { ListNodel * tmp = new ListNodel(key); mapkl.insert(map<int,ListNodel<em>>::value_type(key,tmp)); head = tmp; tail = tmp; head->next = tail; tail->before = head; tail->next = NULL; } else { ListNodel * tmp = new ListNodel(key); mapkl.insert(map<int,ListNodel</em>>::value_type(key,tmp)); tmp->before = tail; tail->next = tmp; tmp->next = NULL; tail = tmp; } } void update(int key) { map<int,ListNodel*>::iterator it = mapkl.find(key); ListNodel * tmp = it->second; if(tmp == head) { if(head->next != NULL) { head = head->next; tail->next = tmp; tmp->before = tail; tmp->next = NULL; tail = tmp; } //delete(tmp); } else if(tmp == tail){</p> <pre><code> } else { ListNodel * tmpb = tmp-&gt;before; ListNodel * tmpn = tmp-&gt;next; tmpb-&gt;next = tmpn; tmpn-&gt;before = tmpb; tmp-&gt;before = tail; tail-&gt;next = tmp; tmp-&gt;next = NULL; tail = tmp; } } </code></pre> <p>};