146. LRU 缓存机制
class LRUCache {
private:
struct DLinkedNode
{
int key, val;
DLinkedNode* prev;
DLinkedNode* next;
DLinkedNode():key(0), val(0), prev(nullptr), next(nullptr){}
DLinkedNode(int _key, int _val):key(_key), val(_val), prev(nullptr), next(nullptr){}
};
unordered_map<int, DLinkedNode*> cache;
int size;
int capacity;
DLinkedNode* head;
DLinkedNode* tail;
void moveToBack(DLinkedNode* ptr)
{
if (ptr->prev != nullptr && ptr->next != nullptr)
{
ptr->prev->next = ptr->next;
ptr->next->prev = ptr->prev;
}
ptr->prev = tail->prev;
tail->prev->next = ptr;
ptr->next = tail;
tail->prev = ptr;
return;
}
void deleteFront()
{
DLinkedNode* tmp = head->next;
tmp->next->prev = head;
head->next = tmp->next;
delete(tmp);
return;
}
public:
LRUCache(int capacity) {
this->capacity = capacity;
size = 0;
head = new DLinkedNode();
tail = new DLinkedNode();
head->next = tail;
tail->prev = head;
}
int get(int key) {
if (cache.find(key) == cache.end())
{
return -1;
}
else
{
moveToBack(cache[key]);
return cache[key]->val;
}
}
void put(int key, int value) {
if (cache.find(key) == cache.end())
{
cache[key] = new DLinkedNode(key, value);
++size;
}
else
{
cache[key]->val = value;
}
moveToBack(cache[key]);
if (size > capacity)
{
cache.erase(head->next->key);
deleteFront();
--size;
}
return;
}
};
/**
* 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);
*/
148. 排序链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if (head == nullptr || head->next == nullptr)
return head;
ListNode* front = new ListNode(0, sortList(head->next));
ListNode* last = front;
ListNode* back = front->next;
while (back != nullptr && back->val < head->val)
{
last = back;
back = back->next;
}
last->next = head;
head->next = back;
return front->next;
}
};
155. 最小栈
class MinStack {
private:
stack<int> sta;
stack<int> min;
public:
/** initialize your data structure here. */
MinStack() {
min.push(INT_MAX);
}
void push(int x) {
sta.push(x);
if (x <= min.top())
{
min.push(x);
}
}
void pop() {
if (sta.top() == min.top())
{
min.pop();
}
sta.pop();
}
int top() {
return sta.top();
}
int getMin() {
return min.top();
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/