Skip to content

Instantly share code, notes, and snippets.

@ajx42
Created November 27, 2023 22:32
Show Gist options
  • Save ajx42/a91119e3b57310f913798a7576b7dfb0 to your computer and use it in GitHub Desktop.
Save ajx42/a91119e3b57310f913798a7576b7dfb0 to your computer and use it in GitHub Desktop.
LRU from Leetcode
class LRUCache {
struct node{
node* next;
node* pre;
int val;
int key;
node() : next(NULL), pre(NULL) {}
};
node* head;
node* tail;
int capacity;
int curr_size;
unordered_map <int, node*> look_up;
void move_to_tail(node* curr){
if(curr != head and curr != tail){
auto pre_node = curr->pre;
auto next_node = curr->next;
pre_node->next = next_node;
next_node->pre = pre_node;
tail->next = curr;
curr->pre = tail;
curr->next = NULL;
tail = curr;
}
else if(curr != tail){
tail->next = curr;
auto next_node = curr->next;
next_node->pre = NULL;
head = next_node;
curr->next = NULL;
curr->pre = tail;
tail = curr;
}
}
public:
LRUCache(int capacity) : curr_size(0), capacity(capacity), head(NULL), tail(NULL) {
}
int get(int key) {
if(look_up.find(key) == look_up.end())
return -1;
else{
move_to_tail(look_up[key]);
return look_up[key]->val;
}
}
void put(int key, int value) {
if(look_up.find(key) == look_up.end()){
if(tail == NULL){
tail = new node;
head = tail;
}
else{
tail->next = new node;
tail->next->pre = tail;
tail = tail->next;
}
look_up[key] = tail;
tail->val = value;
tail->key = key;
curr_size++;
if(curr_size > capacity){
curr_size--;
look_up.erase(head->key);
head->next->pre = NULL;
auto new_head = head->next;
delete head;
head = new_head;
}
}
else{
look_up[key]->val = value;
move_to_tail(look_up[key]);
}
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment