AM/FB 134. LRU Cache
class node{
public:
node *left, *right;
int val, key;
node(int val, int key){
this->val = val;
this->key = key;
this->left = NULL;
this->right = NULL;
}
};
class LRUCache {
public:
/*
* @param capacity: An integer
*/
int cap;
unordered_map<int, node*> hmap;
int cnt;
node *head;
node *tail;
LRUCache(int capacity) {
// do intialization if necessary
cap = capacity;
cnt = 0;
head = new node(0, 0);
tail = new node(0, 0);
head->right = tail;
tail->left = head;
}
/*
* @param key: An integer
* @return: An integer
*/
int get(int key) {
// write your code here
if(hmap.count(key)){
//先把hmap[k]地方断开(建立新的连接)
node *valNode = hmap[key];
node* right = valNode->right;
valNode->left->right = right;
right->left = valNode->left;
// 把hmap[k] node放到开头
moveToHead(valNode);
return valNode->val;
}
return -1;
}
void moveToHead(node* nd){
node* right1 = head->right;
head->right = nd;
nd->right = right1;
nd->left = head;
right1->left = nd;
return;
}
/*
* @param key: An integer
* @param value: An integer
* @return: nothing
*/
void set(int key, int value) {
// write your code here
if(hmap.find(key) != hmap.end()){
hmap[key]->val = value;
//不要忘记先把hmap[key]地方断开。
node *valNode = hmap[key];
node* right = valNode->right;
valNode->left->right = right;
right->left = valNode->left;
//移到开头
moveToHead(hmap[key]);
}
else{
node *add = new node(value, key);
hmap[key] = add;
moveToHead(add);
cnt++;
if(cnt > cap){
//去掉尾巴
//node *tmp = tail->left;
//node *pre = tail->left->left;
//pre->right = tail;
//tail->left = pre;
//更简洁的写法
hmap.erase(tail->left->key);
tail->left->left->right = tail;
tail->left = tail->left->left;
cnt = cap;
}
}
return;
}
};
Comments
Post a Comment