看别人的答案:
1 struct CacheNode { 2 int key, value; 3 CacheNode(int a, int b) : key(a), value(b) { } 4 }; 5 class LRUCache{ 6 public: 7 LRUCache(int capacity) { 8 size = capacity; 9 } 10 11 int get(int key) { 12 if (cacheMap.find(key) == cacheMap.end()) return -1; 13 else { 14 cachelist.splice(cachelist.begin(), cachelist, cacheMap[key]); 15 cacheMap[key] = cachelist.begin(); 16 return cacheMap[key]->value; 17 } 18 } 19 20 void set(int key, int value) { 21 if (cacheMap.find(key) == cacheMap.end()) { 22 if (cachelist.size() == size) { 23 cacheMap.erase(cachelist.back().key); 24 cachelist.pop_back(); 25 } 26 cachelist.push_front(CacheNode(key, value)); 27 cacheMap[key] = cachelist.begin(); 28 } 29 else { 30 cacheMap[key]->value = value; 31 cachelist.splice(cachelist.begin(), cachelist, cacheMap[key]); 32 cacheMap[key] = cachelist.begin(); 33 } 34 } 35 36 private: 37 list<CacheNode> cachelist; 38 unordered_map<int, list<CacheNode>::iterator> cacheMap; 39 int size; 40 };
自己写了另一段更容易懂的代码:
1 struct node { 2 int key; 3 int val; 4 node* next; 5 node(int k, int v) : key(k), val(v), next(NULL) { } 6 }; 7 class LRUCache{ 8 public: 9 LRUCache(int capacity) { 10 len = capacity; 11 } 12 13 int get(int key) { 14 if (!head) return -1; 15 if (head->key == key) return head->val; 16 node* p = head; 17 int cur = 1; 18 while (p->next && cur < len) { 19 cur++; 20 if (p->next->key == key) { 21 node* q = p->next;; 22 p->next = p->next->next; 23 q->next = head; 24 head = q; 25 return head->val; 26 } 27 p = p->next; 28 } 29 return -1; 30 } 31 32 void set(int key, int value) { 33 if (!head) head = new node(key, value); 34 else { 35 node* p = new node(key, value); 36 p->next = head; 37 head = p; 38 int cur = 1; 39 while (p->next && cur < len) { 40 cur++; 41 if (p->next->key == key) { 42 p->next = p->next->next; 43 break; 44 } 45 p = p->next; 46 } 47 } 48 } 49 private: 50 node* head = NULL; 51 int len; 52 };
C#
1 public class node { 2 public int key; 3 public int val; 4 public node next; 5 public node(int k, int v) { 6 key = k; 7 val = v; 8 next = null; 9 } 10 }; 11 public class LRUCache { 12 13 public LRUCache(int capacity) { 14 head = null; 15 len = capacity; 16 } 17 18 public int Get(int key) { 19 if (head == null) return -1; 20 if (head.key == key) return head.val; 21 node p = head; 22 int cur = 1; 23 while (p.next != null && cur < len) { 24 cur++; 25 if (p.next.key == key) { 26 node q = p.next; 27 p.next = p.next.next; 28 q.next = head; 29 head = q; 30 return head.val; 31 } 32 p = p.next; 33 } 34 return -1; 35 } 36 37 public void Set(int key, int value) { 38 if (head == null) head = new node(key, value); 39 else { 40 node p = new node(key, value); 41 p.next = head; 42 head = p; 43 int cur = 1; 44 while (p.next != null && cur < len) { 45 cur++; 46 if (p.next.key == key) { 47 p.next = p.next.next; 48 break; 49 } 50 p = p.next; 51 } 52 } 53 } 54 node head; 55 int len; 56 }