zoukankan      html  css  js  c++  java
  • LeetCode501.二叉搜索树中的众数

    题目

    分析(树为普通二叉树)

    如果将本题的BST树换为普通的一棵树,应该怎么做?map来保存出现的值和频率之间的关系,然后对map的value进行排序,输出最大的value所对应的key。

    代码

     1 class Solution {
     2 public:
     3     vector<int>ans;  //存放最终结果
     4     map<int,int>m;   //key-值,value-出现的频率
     5     void dfs(TreeNode* root){
     6         if(root == NULL) return;
     7         dfs(root->left);
     8         m[root->val]++;
     9         dfs(root->right);
    10     }
    11     static bool cmp(pair<int,int>p1,pair<int,int>p2){
    12         return p1.second > p2.second;
    13     }
    14     vector<int> findMode(TreeNode* root) {
    15         dfs(root);
    16         int cnt = 0;
    17         vector<pair<int,int>>res(m.begin(),m.end());  //将map转换为vector对value进行排序
    18         sort(res.begin(),res.end(),cmp);
    19         for(auto it = res.begin();it != res.end();it++){
    20            if(it->second >= cnt){
    21                 cnt = it->second;
    22                 ans.push_back(it->first);
    23             }else break;
    24         }
    25        return ans;
    26     }
    27 };

    注意:

    map里面存放是按照key有序存放,而不是value,如果想要对map中的value排序,不能直接用sort函数,要先将map转换为vector,再用sort进行排序。

    分析(树为BST二叉树)

    要利用BST树的性质,即中序遍历是递增有序的。利用BST树的常用技巧:双指针,一个指针指向上一个访问的结点,一个指针指向当前结点。普通想法应该是先遍历一遍数组,找出最大频率(maxCount),然后再重新遍历一遍数组把出现频率为maxCount的元素放进集合。(因为众数有多个)。那能否进行一次遍历就得到众数集合呢?

    1. 只要当前 cnt == maxCount,就将数值加入集合

    2. 当前 cnt >  maxCount,清空之前集合的内容,再加入这个元素。

    代码

     1 class Solution {
     2 public:
     3     int maxCnt = 0,cnt = 0;
     4     TreeNode *pre = NULL;
     5     vector<int>res;
     6     void dfs(TreeNode *cur){
     7         if(cur == NULL) return;
     8         dfs(cur->left);
     9         
    10         if(pre == NULL){  //第一个结点
    11             cnt = 1;
    12         }else if(pre->val == cur->val){
    13             cnt++;
    14         }else{
    15             cnt = 1;
    16         }
    17         pre = cur;
    18 
    19         if(cnt == maxCnt){
    20             res.push_back(cur->val);
    21         }else if(cnt > maxCnt){
    22             maxCnt = cnt;
    23             res.clear();
    24             res.push_back(cur->val);
    25         }
    26 
    27         dfs(cur->right); 
    28     }
    29     vector<int> findMode(TreeNode* root) {
    30         dfs(root);
    31         return res;
    32     }
    33 };
  • 相关阅读:
    百度云如何免费扩容至2055G?
    OKR学习总结
    layui和bootstrap 对比
    使用马克飞象+印象笔记 如何简单便捷地发表博客?
    Sublime使用记录之SublimeServer插件介绍
    12.RcolorBrewer包
    11.R语言流程
    25.conda 下载安装与运用
    7、purge_haplogs 基因组去冗余
    5.MCScanX 与circos下载、安装、运用
  • 原文地址:https://www.cnblogs.com/fresh-coder/p/14236903.html
Copyright © 2011-2022 走看看