- DFS and BFS
layer sequence traverses BFS, and a variable level of the number of layers needs to be maintained. Refer to the template and solve DFS and BFS of this question.
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);
}
}
}
- Fast sorting thought The
function returns the subscript of the axis value, and the number group is divided into two parts. Reference source: Classic problem: Find the smallest K value
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;
}
-
Heap sorting: the use of priority_queue
-
Double pointer circular linked list judgment
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;
}
};