...
代码块 |
---|
vector<int> visited; void bfs(vector<vector<int>> &graph, int start) { queue<int> q; q.push(start); visited[start] = 1; while(!q.empty()) { int size = q.size(); while(size-- > 0) { int cur = q.front(); q.pop(); visited[cur] = 1; for(auto nxt : graph[n]) { if(!visited[nxt]) { q.push(nxt); visited[nxt] = 1; } } } } } |
数组元素循环右移n个元素的方法:
先反转开头的n个元素,再反转剩下的元素,再反转整个数组。
对一维数组vector进行首尾填充:
代码块 |
---|
vector<int> nums = {1,2,3,4};
nums.insert(nums.begin(), 0);
nums.push_back(5); |
二叉树的中序遍历,一定是将所有结点按从小到大的顺序输出。
使用递归收集与root距离为d的结点
代码块 |
---|
void collect(TreeNode *root, int d) {
if(root == nullptr || d < 0) {
return;
}
if(d == 0) {
ans.push_back(root->val);
}
collect(root->left, d - 1);
collect(root->right, d - 1);
} |
翻转链表:
代码块 |
---|
list* reverse(list *head)
{
if(!head || !(head->next))
return head;
list *pre = head;
list *p = head->next;
list *next = NULL;
while(p)
{
next = p->next;
p->next = pre;
pre = p;
p = next;
}
head->next = NULL;
return pre;
} |
给定一个数组nums,求nums的所有排列组合,不能重复。
构造并查集时如果没有直接提供整数型编号,比如对一堆字符串建立并查集,可以先将每个字符串映射成唯一的数字,使用map<string, int>配合自增来实现。