[LeetCode] 310. Minimum Height Trees Java

题目:

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]

题意及分析:给出一个无向图,求能形成树的最矮的树的根节点。我首先想到的是用bfs,先保存每个点的邻节点。然后使用bfs遍历当前还未被遍历过的邻节点,但是代码运行超时。。。看了网上使用较多的一种方法是,每次删除度为1的点,直至剩下的点小于等于2,那么这1,2个点就是求的结果。

超时代码:

public class Solution {
    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        List<Integer> res = new ArrayList<>();
        int minHeight = Integer.MAX_VALUE;        //当前最小的高度
        HashMap<Integer,List<Integer>> neighbors = new HashMap<>();  //key为节点,list为该节点的邻接节点
        for(int i=0;i<edges.length;i++){        //找出每个点的邻接节点,这样方便查找
            if(neighbors.containsKey(edges[i][0])){
                neighbors.get(edges[i][0]).add(edges[i][1]);
            }else{
                List<Integer>  list = new ArrayList<>();
                list.add(edges[i][1]);
                neighbors.put(edges[i][0],list);
            }
            if(neighbors.containsKey(edges[i][1])){
                neighbors.get(edges[i][1]).add(edges[i][0]);
            }else{
                List<Integer>  list = new ArrayList<>();
                list.add(edges[i][0]);
                neighbors.put(edges[i][1],list);
            }
        }
        for(int i=0;i<n;i++){       //对每个节点求其高度
            int max = 0;        //以点i为跟节点时,树的最高高度
            boolean[] visited = new boolean[n];     //记录该点是否被遍历过
            Queue<Integer> queue = new LinkedList<>();
            Queue<Integer> tempQueue = new LinkedList<>();      //用来记录下一层节点
            queue.add(i);
            max++;
            while(!queue.isEmpty()||!tempQueue.isEmpty()){
                if(!queue.isEmpty()){        //遍历一层
                    int a = queue.poll();
                    visited[a] = true;
                    if(neighbors.get(a)!=null){
                        for(int j=0;j<neighbors.get(a).size();j++){ //未被遍历过的邻节点添加进queue
                            int neighbor = neighbors.get(a).get(j);
                            if(!visited[neighbor]) tempQueue.add(neighbor);
                        }
                    }
                }else{      //讲下一层数据添加当前层
                    if(!tempQueue.isEmpty())  //下一层不为空,层数加一
                        max++;
                    queue = new LinkedList<>(tempQueue);
                    tempQueue.clear();;
                }
            }
            if(max<minHeight){
                minHeight=max;
                res.clear();
                res.add(i);
            }else if(max==minHeight){
                res.add(i);
            }
        }
        return res;
    }
}

 第二种方法(直接使用一个map[]数组保存是否入度,但是这样删除入度为1的点时需要遍历数组查找,时间复杂度还是较大):

public class Solution {
    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        List<Integer> res = new ArrayList<>();
        for(int i=0;i<n;i++){
            res.add(i);
        }
        if(res.size()<=2) return res;
        int[] map = new int[n];
        for(int i=0;i<edges.length;i++){        //找出每个点的邻接节点,这样方便查找
            map[edges[i][0]]++;
            map[edges[i][1]]++;
        }

        Queue<Integer> queue = new LinkedList<>();
        Queue<Integer> tempQueue = new LinkedList<>();       //用来记录下一层需要删除的点
        for(int i=0;i<map.length;i++){
            if(map[i]==1) queue.add(i);     //最初始度为1的点
        }
        while((!queue.isEmpty()||!tempQueue.isEmpty())){
            if (!queue.isEmpty()){
                int temp = queue.poll();
                res.remove((Object)temp);       //删除度为1的点,且重置度
                for(int i = 0;i<edges.length;i++){      //找到以该节点为边的点,将值该点和邻节点度减1
                    if(edges[i][0]==temp){
                        map[temp]--;        //为0了。
                        map[edges[i][1]]--;
                        if(map[edges[i][1]]==1){
                            tempQueue.add(edges[i][1]); //删除该点后若和该点相连的点度也变成1则添加进queue
                        }
                    }
                    if(edges[i][1]==temp){
                        map[temp]--;
                        map[edges[i][0]]--;
                        if(map[edges[i][0]]==1){
                            tempQueue.add(edges[i][0]); //删除该点后若和该点相连的点度也变成1则添加进queue
                        }
                    }
                }
            }else{      //遍历下一层
                queue=new LinkedList<>(tempQueue);
                tempQueue.clear();;
                if(res.size()<=2) break;
            }
        }
        return res;
    }
}

第二种方法:使用一个hashmap保存每个点的所有邻接节点,这样就不需要遍历数组,减少时间复杂度

public class Solution {
    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        List<Integer> res = new ArrayList<>();
        for(int i=0;i<n;i++){
            res.add(i);
        }
        if(res.size()<=2) return res;
        HashMap<Integer,List<Integer>> neighbors = new HashMap<>();  //key为节点,list为该节点的邻接节点
        for(int i=0;i<edges.length;i++){        //找出每个点的邻接节点,这样方便查找
            if(neighbors.containsKey(edges[i][0])){
                neighbors.get(edges[i][0]).add(edges[i][1]);
            }else{
                List<Integer>  list = new ArrayList<>();
                list.add(edges[i][1]);
                neighbors.put(edges[i][0],list);
            }
            if(neighbors.containsKey(edges[i][1])){
                neighbors.get(edges[i][1]).add(edges[i][0]);
            }else{
                List<Integer>  list = new ArrayList<>();
                list.add(edges[i][0]);
                neighbors.put(edges[i][1],list);
            }
        }
        Queue<Integer> queue = new LinkedList<>();
        for(int i=0;i<n;i++){
            if(neighbors.get(i)!=null){
                if(neighbors.get(i).size()==1){
                    queue.add(i);
                }
            }
        }
        Queue<Integer> tempQueue = new LinkedList<>();
        while (!queue.isEmpty()||!tempQueue.isEmpty()){
            if(!queue.isEmpty()){
                int temp = queue.poll();        //查找该点的邻节点
                res.remove((Object)temp);
                List<Integer> neighbor = neighbors.get(temp);       //度为1的点的邻节点肯定只有一个
                for(int i=0;i<neighbor.size();i++){     //在邻节点中删除节点
                    neighbors.get(neighbor.get(i)).remove((Object)temp);
                    if(neighbors.get(neighbor.get(i)).size()==1){       //入度为1
                        tempQueue.add(neighbor.get(i));
                    }
                }
            }else{
                queue = new LinkedList<>(tempQueue);
                tempQueue.clear();
                if(res.size()<=2)
                    break;
            }
        }
        return res;
    }
}

 

转载于:https://www.cnblogs.com/271934Liao/p/7248988.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用Java中的排序功能来实现。可以使用Arrays.sort()函数,将列表中的元素按照字母顺序排序,或者使用Collections.sort()函数,将列表中的元素按用户指定的排序规则排序。 ### 回答2: 为了实现LeetCode 2561题(Rearranging Fruits)的要求,需要使用Java编程语言。主要思路是遍历给定的水果数组,同时用一个哈希表来记录每个水果出现的次数。然后根据题目要求,重新排列水果使得相同类型的水果尽可能接近,并且按照出现次数的非递增顺序排序。 具体实现步骤如下: 1. 创建一个HashMap来存储每个水果的出现次数。遍历给定的水果数组,如果该水果已经存在于HashMap中,则将其出现次数加1;否则,将该水果添加到HashMap,并将其出现次数初始化为1。 2. 创建一个ArrayList来存储已经排列好的水果。通过HashMap的entrySet方法获取到每种水果和它的出现次数,然后将这些entry按照出现次数的非递增顺序进行排序。 3. 遍历排序好的entry集合,根据每个水果的出现次数,在ArrayList中连续添加相应数量的水果。 4. 返回排列好的水果数组。 以下是Java代码的示例实现: ```java import java.util.*; class Solution { public String[] rearrange(String[] fruits) { HashMap<String, Integer> fruitCountMap = new HashMap<>(); // 统计每个水果的出现次数 for (String fruit : fruits) { if (fruitCountMap.containsKey(fruit)) { fruitCountMap.put(fruit, fruitCountMap.get(fruit) + 1); } else { fruitCountMap.put(fruit, 1); } } ArrayList<Map.Entry<String, Integer>> sortedEntries = new ArrayList<>(fruitCountMap.entrySet()); // 根据出现次数进行非递增排序 Collections.sort(sortedEntries, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2) { return entry2.getValue().compareTo(entry1.getValue()); } }); ArrayList<String> rearrangedFruits = new ArrayList<>(); // 根据出现次数连续添加水果 for (Map.Entry<String, Integer> entry : sortedEntries) { String fruit = entry.getKey(); int count = entry.getValue(); for (int i = 0; i < count; i++) { rearrangedFruits.add(fruit); } } return rearrangedFruits.toArray(new String[0]); } } ``` 使用以上代码,可以对给定的水果数组进行重新排列,使得相同类型的水果尽可能接近,并且按照出现次数的非递增顺序进行排序。返回的结果就是排列好的水果数组。 ### 回答3: 题目要求将一个字符串中的水果按照特定规则重新排列。我们可以使用Java来实现这个问题。 首先,我们需要定义一个函数来解决这个问题。 ```java public static String rearrangeFruits(String fruits) { // 将字符串转换为字符数组方便处理 char[] fruitArray = fruits.toCharArray(); // 统计每种水果的数量 int[] fruitCount = new int[26]; for (char fruit : fruitArray) { fruitCount[fruit - 'a']++; } // 创建一个新的字符数组来存储重新排列后的结果 char[] rearrangedFruitArray = new char[fruitArray.length]; // 逐个将水果按照规则放入新数组中 int index = 0; for (int i = 0; i < 26; i++) { while (fruitCount[i] > 0) { rearrangedFruitArray[index++] = (char) ('a' + i); fruitCount[i]--; } } // 将字符数组转换为字符串并返回 return new String(rearrangedFruitArray); } ``` 上述代码中,我们首先将字符串转换为字符数组,并使用一个长度为26的数组来统计每一种水果的数量。然后,我们创建一个新的字符数组来存储重新排列后的结果。 接下来,我们利用双重循环将每一种水果按照规则放入新数组中。最后,我们将字符数组转换为字符串并返回。 例如,如果输入字符串为`"acbba"`,则经过重新排列后,输出结果为`"aabbc"`。 这样,我们就用Java实现了题目要求的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值