码迷,mamicode.com
首页 > 其他好文 > 详细

310. Minimum Height Trees

时间:2016-03-06 07:42:43      阅读:315      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/neweracoding/p/5246487.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!