Leetcode#146 LRU Cache

原题地址

 

以前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 };

 

转载于:https://www.cnblogs.com/boring09/p/4234034.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值