代码随想录算法训练营第十三天| 235. 二叉搜索树的最近公共祖先|239. 滑动窗口最大值| 347.前 K 个高频元素|

235. 二叉搜索树的最近公共祖先

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
    TreeNode* dfs(TreeNode* root, TreeNode* p, TreeNode* q){
        if(root==NULL){
            return root;
        }

        if(root->val>p->val&&root->val>q->val){
            TreeNode*left = dfs(root->left,p,q);
            if(left!=NULL){
                return left;
           }
        } 
        if(root->val<p->val&&root->val<q->val){
            TreeNode*right = dfs(root->right,p,q);
            if(right!=NULL){
                return right;
           }
        } 
        return root;
    }
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        return dfs(root,p,q);
    }
};

239. 滑动窗口最大值


class MyQueue {
    deque<int>que;
public:
    void push(int x) {
        while(!que.empty()&&que.back()<x){
            que.pop_back();
        }
        que.push_back(x);
    }
    void pop(int x){
        if(!que.empty()&&que.front()==x){
            que.pop_front();
        }
    }
    int front(){
        return  que.front();
    }
};
class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        MyQueue que;
        vector<int>res;
        for(int i=0;i<k;i++){
            que.push(nums[i]);
        }
        res.push_back(que.front());
        for(int i=k,j=0;i<nums.size();i++,j++){
            que.pop(nums[j]);
            que.push(nums[i]);
            res.push_back(que.front());
        }
        return res;
    }
};

347.前 K 个高频元素

class Solution {
public:

    static bool cmp(pair<int,int>&a,pair<int,int>&b){
        return a.second>b.second;
    }
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int,int>mp;
        vector<int>res;
        for(unsigned int i = 0;i<nums.size();i++){
            mp[nums[i]]++;
        }
        vector<pair<int,int>>vec(mp.begin(),mp.end());
        sort(vec.begin(),vec.end(),cmp);
        for(int i=0;i<k;i++){
            res.push_back(vec[i].first);
        }
        return res;

    }
};

你可能感兴趣的:(算法,深度优先,数据结构)