Algorithm question template (to be added)

  1. 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);
        }
    }
    //return ...
}
  1. 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;
    }
  1. Heap sorting: the use of priority_queue

  2. Double pointer circular linked list judgment

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
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;
    }
};

Guess you like

Origin blog.csdn.net/qq_43078427/article/details/112460686