本文链接:
https://blog.csdn.net/qq_34811382/article/details/113062636
146. LRU 缓存机制
思路:
哈希表+双向链表实现
代码:
class DLinkedNode {
public:
int key;
int val;
DLinkedNode* pre;
DLinkedNode* next;
DLinkedNode() : key(0), val(0), pre(nullptr), next(nullptr) {
}
DLinkedNode(int _key, int _val) : key(_key), val(_val), pre(nullptr), next(nullptr) {
}
};
class LRUCache {
public:
LRUCache(int _capacity) {
size = 0;
capacity = _capacity;
head = new DLinkedNode(); // dummy head
tail = new DLinkedNode(); // dummy tail
head->next = tail;
tail->pre = head;
}
int get(int key) {
if (!cache.count(key)) {
return -1;
}
auto* node = cache[key];
moveToHead(node);
return node->val;
}
void put(int key, int value) {
if (cache.count(key)) {
// update the value
auto* node = cache[key];
// Since we are using pointer, no need to delete and re-add
node->val = value;
moveToHead(node);
} else {
if (size == capacity) {
auto tail = removeTail();
// Delete from cache, but not free
cache.erase(tail->key);
// Free the memory
delete tail;
size--;
}
auto* node = new DLinkedNode(key, value);
cache[key] = node;
addToHead(node);
size++;
}
}
void addToHead(DLinkedNode* node) {
head->next->pre = node;
node->next = head->next;
head->next = node;
node->pre = head;
}
void untie(DLinkedNode* node) {
node->pre->next = node->next;
node->next->pre = node->pre;
}
DLinkedNode* removeTail() {
auto node = tail->pre;
untie(node);
return node;
}
void moveToHead(DLinkedNode* node) {
untie(node);
addToHead(node);
}
private:
int size;
int capacity;
DLinkedNode* head;
DLinkedNode* tail;
unordered_map<int, DLinkedNode*> cache;
};
148. 排序链表
思路:
二路归并+递归
将链表逐渐二分,每个二分之间进行排序,在综合成两个链表排序
代码:
class Solution
{
public:
ListNode *sortList(ListNode *head)
{
if (head == nullptr || head->next == nullptr)
return head;
ListNode *res;
ListNode *slow = head, *fast = head;
while (fast->next != nullptr && fast->next->next != nullptr)
{
slow = slow->next;
fast = fast->next->next;
}
fast = slow->next;
slow->next = nullptr;
slow = head;
res = MergeTwoList(sortList(slow), sortList(fast));
return res;
}
ListNode *MergeTwoList(ListNode *l1, ListNode *l2)
{
if (l1 == nullptr)
return l2;
if (l2 == nullptr)
return l1;
if (l1->val <= l2->val)
{
l1->next = MergeTwoList(l1->next, l2);
return l1;
}
if (l1->val > l2->val)
{
l2->next = MergeTwoList(l1, l2->next);
return l2;
}
return nullptr;
}
};
155 最小栈
思路:
站在巨人的肩膀上,利用现成的容器stack
借助栈的性质,FILO,用一个辅助栈,来记录每次添加新数据入栈后,让最小的数保持在栈顶。
比如输入的数据是{1,-1,0,-2,3},则在栈中存储为{3,-2,0,-1,1] },在最小栈中为{-2,-2,-1,-1,1] }=>’]'表示栈底
代码:
class MinStack
{
public:
stack<int> FuzhuStack;
stack<int> Min_Stack;
MinStack()
{
Min_Stack.push(INT_MAX);
}
void push(int x)
{
Min_Stack.push(min(Min_Stack.top(), x));
FuzhuStack.push(x);
}
void pop()
{
FuzhuStack.pop();
Min_Stack.pop();
}
int top()
{
return FuzhuStack.top();
}
int getMin()
{
return Min_Stack.top();
}
};