【Lintcode】872. Kill Process

题目地址:

https://www.lintcode.com/problem/kill-process/description

给定两个整数数组 A A A B B B表示进程名,长度相等,每个位置表示 A [ i ] A[i] A[i]的父进程是 B [ i ] B[i] B[i]。现在给定一个进程 k k k,要求杀死此进程后所有被终止的进程的进程名。某个进程被杀死后其自己和其子孙节点都会被终止。题目保证进程之间父子的关系是森林的形式,也就是没有环。

本质上就是多叉树的搜索。首先建图,然后DFS即可。代码如下:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution {
    /**
     * @param pid: the process id
     * @param ppid: the parent process id
     * @param kill: a PID you want to kill
     * @return: a list of PIDs of processes that will be killed in the end
     */
    public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) {
        // Write your code here
        List<Integer> res = new ArrayList<>();
        
        // key表示进程名,value表示其(直接)子进程的进程名
        Map<Integer, List<Integer>> graph = new HashMap<>();
        for (int i = 0; i < pid.size(); i++) {
            graph.putIfAbsent(ppid.get(i), new ArrayList<>());
            graph.get(ppid.get(i)).add(pid.get(i));
        }
        
        dfs(kill, graph, res);
        return res;
    }
    
    private void dfs(int id, Map<Integer, List<Integer>> graph, List<Integer> res) {
        res.add(id);
        if (graph.containsKey(id)) {
            for (int child : graph.get(id)) {
                dfs(child, graph, res);
            }
        }
    }
}

时空复杂度 O ( V + E ) O(V+E) O(V+E)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值