leetcode 582. Kill Process
来源:互联网 发布:美工穿什么衣服 编辑:程序博客网 时间:2024/06/07 19:51
Given n processes, each process has a unique PID (process id) and its PPID (parent process id).Each process only has one parent process, but may have one or more children processes. This is just like a tree structure. Only one process has PPID that is 0, which means this process has no parent process. All the PIDs will be distinct positive integers.We use two list of integers to represent a list of processes, where the first list contains PID for each process and the second list contains the corresponding PPID.Now given the two lists, and a PID representing a process you want to kill, return a list of PIDs of processes that will be killed in the end. You should assume that when a process is killed, all its children processes will be killed. No order is required for the final answer.Example 1:Input: pid = [1, 3, 10, 5]ppid = [3, 0, 5, 3]kill = 5Output: [5,10]Explanation: 3 / \ 1 5 / 10Kill 5 will also kill 10.Note:The given kill id is guaranteed to be one of the given PIDs.n >= 1.
主要注意不能超时
最蠢的方法是构建一个队列,一个一个的扩展孩子,一次次的遍历ppid。
一种先遍历一遍ppid,构建一个HashMap, key 为ppid,value为以key为父节点的集合。
public class Solution { public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) { ArrayList<Integer> res = new ArrayList<>(); HashMap<Integer, ArrayList<Integer>> nbMap = new HashMap<>(); for(int i=0; i<ppid.size(); i++){ int p_value = ppid.get(i); ArrayList<Integer> value = nbMap.getOrDefault(p_value, new ArrayList<>()); if(value.size()==0){ value.add(pid.get(i)); nbMap.put(p_value, value); }else{ value.add(pid.get(i)); } } res.add(kill); ArrayList<Integer> child = nbMap.getOrDefault(kill, null); if(child!=null) addChild(child, res, nbMap); return res; } public void addChild(ArrayList<Integer> child, ArrayList<Integer> res, HashMap<Integer, ArrayList<Integer>> nbMap){ res.addAll(child); for(int i=0; i< child.size(); i++){ ArrayList<Integer> tp = nbMap.getOrDefault(child.get(i), null); if(tp!=null){ addChild(tp, res, nbMap); } } }}
这里一个巧妙的地方是addChild方法。
如果不这样,需要创建一个临时list,把child中每个元素扩展的节点都加进去,这个加入过程可能费时间。不如直接分开做。
阅读全文
0 0
- [leetcode] 582. Kill Process
- leetcode 582.Kill Process
- leetcode 582. Kill Process
- Leetcode 582. Kill Process 题解
- [leetcode contest 582. Kill Process]week 14
- LeetCode-582. Kill Process (JAVA)杀死进程
- Leetcode:Kill Process
- 20170529-leetcode-582-Kill process
- 582. Kill Process Medium
- 582. Kill Process
- 582. Kill Process
- 582. Kill Process
- 582. Kill Process(Medium)
- Kill Process
- kill process
- kill process
- kill process
- Kill Process
- 使用sklearn优雅地进行数据挖掘
- ubuntu安装vue
- Linux修改文件夹及文件权限
- 数据结构(图遍历--广度优先遍历)
- unity网络连接的学习
- leetcode 582. Kill Process
- [bzoj4403]序列统计 Lucas定理
- 使用firewall-cmd命令配置防火墙
- Divide_Two_Integers
- 网易春招面试题--搬砖
- Activity之间跳转和参数传递
- Linux shell实现MySQL数据库简单查询&&MySQL多表联合查询
- 安卓SharedPreferences存储与读取
- 如何通俗地理解 Gradle?