算法题常用 CPP API
结构体
struct Node {
int val;
Node* next;
Node(int x) : val(x), next(nullptr) {}
};
数组
一维数组
#include <vector>
#include <algorithm>
vector<int> nums = {1, 2, 3};
nums.size(); // 获取大小
nums.empty(); // 判空
nums.push_back(4); // 尾部插入
nums.pop_back(); // 尾部删除
sort(nums.begin(), nums.end()); // 排序
二维数组
#include <vector>
vector<vector<int>> matrix(m, vector<int>(n, 0));
matrix.size(); // 行数
matrix[0].size(); // 列数
栈
#include <stack>
stack<int> stk;
stk.push(1); // 入栈
stk.top(); // 获取栈顶
stk.pop(); // 出栈
stk.empty(); // 判空
队列
#include <queue>
queue<int> q;
q.push(1); // 入队
q.front(); // 获取队首
q.pop(); // 出队
q.empty(); // 判空
堆(优先队列)
#include <queue>
priority_queue<int> maxHeap; // 大顶堆
priority_queue<int, vector<int>, greater<int>> minHeap; // 小顶堆
maxHeap.push(3); // 插入元素
maxHeap.top(); // 获取堆顶
maxHeap.pop(); // 弹出堆顶
哈希表:unordered_set
#include <unordered_set>
unordered_set<int> hashSet;
hashSet.insert(1); // 插入
hashSet.erase(1); // 删除
hashSet.count(1); // 判断存在
hashSet.size(); // 元素数量
键值哈希表:unordered_map
#include <unordered_map>
unordered_map<string, int> hashMap;
hashMap["key"] = 1; // 插入/修改
hashMap.erase("key");// 删除
hashMap.count("key");// 判断存在
hashMap.size(); // 元素数量
红黑树:set
#include <set>
set<int> rbSet;
rbSet.insert(1); // 插入
rbSet.erase(1); // 删除
rbSet.count(1); // 判断存在
rbSet.lower_bound(1);// 第一个>=1的元素
键值红黑树:map
#include <map>
map<string, int> rbMap;
rbMap["key"] = 1; // 插入/修改
rbMap.erase("key"); // 删除
rbMap.count("key"); // 判断存在
rbMap.lower_bound("key"); // 第一个>=key的元素
数学相关
#include <algorithm> // for max, min, swap, reverse
#include <cmath> // for abs
#include <numeric> // for __gcd (in some compilers)
max(a, b); // 最大值
min(a, b); // 最小值
abs(x); // 绝对值
swap(a, b); // 交换
reverse(nums.begin(), nums.end()); // 反转
__gcd(a, b); // 最大公约数
内存分配与回收
int* p = new int(5); // 动态分配
delete p; // 释放内存
int* arr = new int[n]; // 动态数组
delete[] arr; // 释放数组