leetcode 582. Kill Process

本文探讨了解决LeetCode 582题目的方法,重点在于避免超时。通过先遍历ppid构建HashMap,优化扩展孩子进程的过程,利用addChild方法提高效率,避免了使用临时list导致的时间消耗。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 = 5
Output: [5,10]
Explanation: 
           3
         /   \
        1     5
             /
            10
Kill 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中每个元素扩展的节点都加进去,这个加入过程可能费时间。不如直接分开做。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值