关闭

LeetCode 310. Minimum Height Trees(超时)

标签: C++leetcodeMinimum Height Trees
74人阅读 评论(0) 收藏 举报
分类:

题目链接: https://leetcode.com/problems/minimum-height-trees/

题目描述:

For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels.

Format
The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels).

You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.

Example 1:

Given n = 4edges = [[1, 0], [1, 2], [1, 3]]

        0
        |
        1
       / \
      2   3

return [1]

Example 2:

Given n = 6edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]

     0  1  2
      \ | /
        3
        |
        4
        |
        5

return [3, 4]

Hint:

  1. How many MHTs can a graph have at most?
思路:首先可以遍历所有的点,将每个结点作为根节点,计算高度,求最小的高度。这种没试,网上说会超时。另外的思路就是一层层剥去叶子节点,最后剩下一个或者两个即为所求,但是我写的还是会超时。。。功能应该实现了,数据比较多的时候超时,,,目前还没有改好。。

代码:

class Solution {
public:
	vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
		vector<int> re;
		if (n == 1)
		{
			re.push_back(0);
			return re;
		}
		map<int, vector<int>> list;
		for (int i = 0; i<n - 1; i++)
		{
			list[edges[i].first].push_back(edges[i].second);
			list[edges[i].second].push_back(edges[i].first);
		}
		map<int, vector<int>> list1;
		while (1)
		{
	    	list1 = list;
			if (list.size() == 1)
			{
				map<int, vector<int>>::iterator j = list.begin();
				re.push_back(j->first);
				break;
			}
			if (list.size() == 2)
			{   
				map<int, vector<int>>::iterator j = list.begin();
				re.push_back(j->first);
				j++;
				re.push_back(j->first);
				break;
			}
			for (map<int, vector<int>>::iterator i = list1.begin(); i != list1.end(); i++)
			{
				if (list1[i->first].size() == 1)
				{
					int tmp = list1[i->first][0];
					list[tmp].erase(find(list[tmp].begin(), list[tmp].end(), i->first));
					list.erase(i->first);
				}
			}
		}
		return re;
	}
};

这应该是倒数第几个测试数据。。。

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:13662次
    • 积分:1359
    • 等级:
    • 排名:千里之外
    • 原创:130篇
    • 转载:6篇
    • 译文:0篇
    • 评论:1条
    最新评论