标签:
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; } }
标签:
原文地址:http://www.cnblogs.com/neweracoding/p/5246487.html