[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:
- The given kill id is guaranteed to be one of the given PIDs.
- 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; }};
- [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
- MAC上charles使用教程总结
- struts2的数据校验
- (六)android recovery 升级UI显示之资源文件
- ffmpeg的相关方法封装
- navicat远程连接mysql出现1130的错误
- [leetcode] 582. Kill Process
- 1.数字证书的知识
- 解析mysql不重复字段值求和
- 杭州落户-人才引进(其他)-挂靠人才中心 办理经验
- mysql数据库的主从复制原理以及减少主从复制的延迟方法
- JAVA中ByteArrayInputStream和ByteArrayOutputStream详解
- RARP协议的使用场景
- 解决Mac空间占用100%
- iOS:WKWebView与UIWebView的区别