- DFS 与 BFS
层序遍历BFS,需要维护一个层数的变量 level。参考模板及本题题解 DFS 与 BFS。
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
while(q.size())
{
int size=q.size();
for(int i=0;i<size;i++)
{
TreeNode* rt=q.front();q.pop();
if(rt->left) q.push(rt->left);
if(rt->right) q.push(rt->right);
}
}
}
- 快排思想
函数返回轴值下标,将数组分治为两部分,参考出处:经典题目:找最小的K个值
int partition(vector<int>& arr, int left, int right) {
int pivot = left;
int lt = left + 1;
int gt = right;
while (true) {
while (lt <= right && arr[lt] < arr[pivot]) lt++;
while (gt >= left && arr[gt] > arr[pivot]) gt--;
if (lt > gt) break;
swap(arr[lt], arr[gt]);
lt++;
gt--;
}
swap(arr[pivot], arr[gt]);
return gt;
}
-
堆排序:优先队列 priority_queue的使用
-
双指针循环链表判断
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head) return false;
ListNode* pre = head;
ListNode* behind = head;
while(pre && behind){
pre = pre->next;
if(behind->next) behind = behind->next->next;
else return false;
if(pre == behind) return true;
}
return false;
}
};