310. Minimum Height Trees
Posted 蜃利的阴影下
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了310. Minimum Height Trees相关的知识,希望对你有一定的参考价值。
Time Limit Exceeded:
import java.lang.reflect.Array; public class Solution { public List<Integer> findMinHeightTrees(int n, int[][] edges) { List<Integer> results = new ArrayList<Integer>(); if(n == 0) return results; ArrayList<Integer>[] adjencencyList = (ArrayList<Integer>[]) Array.newInstance(ArrayList.class, n); for(int i = 0; i<n; ++i) { adjencencyList[i] = new ArrayList<Integer>(); } for(int[] edge: edges) { adjencencyList[edge[0]].add(edge[1]); adjencencyList[edge[1]].add(edge[0]); } Integer[] heightArray = new Integer[n]; for(int i = 0; i<n; ++i) { boolean[] visited = new boolean[n]; visited[i] = true; ArrayList<Integer> level = adjencencyList[i]; int height = 0; while(!level.isEmpty()) { ++ height; ArrayList<Integer> newLevel = new ArrayList<Integer>(); for(Integer node : level) { if(!visited[node]) { visited[node] = true; for(Integer nn: adjencencyList[node]) { if(!visited[nn]) newLevel.add(nn); } } } level = newLevel; } heightArray[i] = height; } Integer minimumHeight = Integer.MAX_VALUE; for(int i=0;i<n;++i) { Integer h = heightArray[i]; if(h<minimumHeight) { minimumHeight = h; results.clear(); } if(h == minimumHeight) { results.add(i); } } return results; } }
以上是关于310. Minimum Height Trees的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 310. Minimum Height Trees 最小高度树(中等)