zoukankan      html  css  js  c++  java
  • LeetCode "Minimum Height Tree" !!

    Simple data structure but not that easy to figure out.. MHT -> balanced tree.
    https://leetcode.com/problems/minimum-height-trees/

    Lesson learnt: Focus on problem itself. Play with it. Do NOT jam your brain with knowledge!

    class Solution 
    {
    public:
        vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) 
        {
            vector<int> ret;
            int m = edges.size();
            if(!m) return {0};
            
            //    Set up Graph
            unordered_set<int> leaves;
            unordered_set<int> all;
            for(int i = 0; i < n; i ++)
            {
                leaves.insert(i);
                all.insert(i);
            }
            if(all.size() < 3)
            {
                for(auto v: all) ret.push_back(v);
                return ret;
            }        
            
            unordered_map<int, unordered_set<int>> g;
            for(auto &p : edges)
            {
                g[p.first].insert(p.second);
                if(g[p.first].size() > 1)
                    leaves.erase(p.first);
                g[p.second].insert(p.first);
                if(g[p.second].size() > 1)
                    leaves.erase(p.second);
            }
            
            queue<int> q;
            for(auto l : leaves)
                q.push(l);
            
            unordered_set<int> cs;
            while(!q.empty())
            {
                int v = q.front(); q.pop();            
                all.erase(v);            
                for(auto c: g[v])
                {
                    if(all.count(c))
                    {
                        g[c].erase(v);
                        if(g[c].size() == 1)
                            cs.insert(c);
                    }
                }
                if(q.empty())
                {
                    if(all.size() <= 2) break;
                
                    for(auto v : cs) q.push(v);
                    cs.clear();
                }                    
            }
            for(auto v: all) ret.push_back(v);
            return ret;
        }
    };
  • 相关阅读:
    redis相关
    Ubuntu安装之python开发
    Shell编程实战
    saltstack高效运维
    docker网络
    docker入门
    python学习博客地址集合。。。
    vue+uwsgi+nginx部署路飞学城
    部署你的CRM程序
    Java Netty教程(目录)
  • 原文地址:https://www.cnblogs.com/tonix/p/4998042.html
Copyright © 2011-2022 走看看