算法题模板(待补充)

  1. 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);
        }
    }
    //return ...
}
  1. 快排思想
    函数返回轴值下标,将数组分治为两部分,参考出处:经典题目:找最小的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;
    }
  1. 堆排序:优先队列 priority_queue的使用

  2. 双指针循环链表判断

/**
 * 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;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_43078427/article/details/112460686
今日推荐