Ruby超时算法:Leetcode 310. Minimum Height Trees 拓扑排序

A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.

Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h)) are called minimum height trees (MHTs).

Return a list of all MHTs’ root labels. You can return the answer in any order.

The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.

Example 1:

Input: n = 4, edges = [[1,0],[1,2],[1,3]]
Output: [1]
Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.

Example 2:

Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
Output: [3,4]

看了答案写的算法,太菜超时了,但也是一种锻炼吧

# @param {Integer} n
# @param {Integer[][]} edges
# @return {Integer[]}
def find_min_height_trees(n, edges)
    # 根据答案拓扑排序写的超时代码
    return [0] if edges.size == 0
    return [0,1] if edges.size == 1
    degree_map = {}
    ramainNodes = n
    for edge in edges
        degree_map[edge[0]] = degree_map[edge[0]] ? (degree_map[edge[0]] + 1) : 1
        degree_map[edge[1]] = degree_map[edge[1]] ? (degree_map[edge[1]] + 1) : 1
    end
    preEdge = [[-1,-1],[-1,-1]]
    while ramainNodes > 2
        for node_no,degree in degree_map.select{|node_no,degree| degree == 1}
            for i in 0...edges.size
                if edges[i].include? node_no
                    degree_map[edges[i][0]] -= 1
                    degree_map[edges[i][1]] -= 1
                    preEdge[0] = preEdge[1]
                    preEdge[1] = edges[i]
                    edges[i] = [-1,-1]
                end
            end
            ramainNodes -= 1
            # break if ramainNodes <= 3
        end
    end
    
    if ramainNodes == 1
        return (preEdge[1].include? preEdge[0][0]) ? [preEdge[0][0]] : [preEdge[0][1]]
    else
        for edge in edges do return edge if edge[0] != -1 end
    end
end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值