[leetcode] 582. Kill Process

来源:互联网 发布:百视通网络电视下载 编辑:程序博客网 时间:2024/06/15 05:03

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:

  1. The given kill id is guaranteed to be one of the given PIDs.
  2. n >= 1.

这道题是杀掉进程及其子进程,题目难度为Medium。

依据PID和PPID两个列表,我们能够统计出每个进程的直接子进程,并将其存入Hash Table,之后便是遍历的问题了。给出要杀掉的进程ID后,在Hash Table中找出其直接子进程列表,可以分别采用深度优先和广度优先的方法进行遍历。

深度优先的方法即采用递归遍历到某个子进程不再有自己的子进程为止,具体代码:

class Solution {    void killAll(int kill, unordered_map<int, vector<int>>& hash, vector<int>& ret) {        ret.push_back(kill);        for(auto id:hash[kill]) killAll(id, hash, ret);    }public:    vector<int> killProcess(vector<int>& pid, vector<int>& ppid, int kill) {        unordered_map<int, vector<int>> hash;        vector<int> ret;                for(int i=0; i<pid.size(); ++i)             hash[ppid[i]].push_back(pid[i]);                    killAll(kill, hash, ret);                return ret;    }};

广度优先的方法借助队列,将子进程依次存入队列,然后逐层找出所有子进程的子进程,直至没有子进程为止,具体代码:

class Solution {public:    vector<int> killProcess(vector<int>& pid, vector<int>& ppid, int kill) {        unordered_map<int, vector<int>> hash;        queue<int> que;        vector<int> ret;                for(int i=0; i<pid.size(); ++i)             hash[ppid[i]].push_back(pid[i]);                    que.push(kill);        while(!que.empty()) {            int sz = que.size();            for(int i=0; i<sz; ++i) {                int cur = que.front();                que.pop();                ret.push_back(cur);                for(auto id:hash[cur]) que.push(id);            }        }                return ret;    }};

原创粉丝点击