以前Leetcode的测试数据比较弱,单纯用链表做也能过,现在就不行了,大数据会超时。通常大家都是用map+双向链表做的。
我曾经尝试用C++的list容器来写,后来发现map没法保存list的iterator,总是报错,我也不知道为什么。后来只好手写双向链表,真是痛苦啊,一不小心就会出错。怪不得这道题是hard
代码:
1 struct Node { 2 int key; 3 int val; 4 Node *prev; 5 Node *next; 6 Node() : prev(NULL), next(NULL) {} 7 Node(int k, int v) : key(k), val(v), prev(NULL), next(NULL) {} 8 }; 9 10 class LRUCache { 11 public: 12 map<int, Node*> index; 13 Node *head; 14 Node *tail; 15 int maxSize; 16 17 LRUCache(int capacity) { 18 maxSize = capacity; 19 head = new Node(); 20 tail = new Node(); 21 head->next = tail; 22 tail->prev = head; 23 } 24 25 int get(int key) { 26 if (index.find(key) == index.end()) 27 return -1; 28 29 Node *node = index[key]; 30 node->prev->next = node->next; 31 node->next->prev = node->prev; 32 node->prev = head; 33 node->next = head->next; 34 head->next->prev = node; 35 head->next = node; 36 37 return node->val; 38 } 39 40 void set(int key, int value) { 41 if (maxSize == 0) 42 return; 43 44 if (index.find(key) != index.end()) { 45 Node *node = index[key]; 46 node->val = value; 47 node->prev->next = node->next; 48 node->next->prev = node->prev; 49 node->prev = head; 50 node->next = head->next; 51 head->next->prev = node; 52 head->next = node; 53 } 54 else { 55 Node *node = new Node(key, value); 56 node->next = head->next; 57 node->prev = head; 58 head->next->prev = node; 59 head->next = node; 60 index[key] = node; 61 if (index.size() > maxSize) { 62 node = tail->prev; 63 tail->prev = node->prev; 64 node->prev->next = tail; 65 index.erase(node->key); 66 delete node; 67 } 68 } 69 } 70 };