LeetCode 582. Kill Process 解题报告
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 582. Kill Process 解题报告相关的知识,希望对你有一定的参考价值。
Problem statement:
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.
思路:利用BFS+HashMap,首先将父进程和子进程存入HashMap。然后利用BFS,这里需要用到队列。当然,这里用DFS也行。
代码:
vector<int> killProcess(vector<int>& pid, vector<int>& ppid, int kill){ unordered_map<int,vector<int>> map; for(int i = 0;i<ppid.size();i++)map[ppid[i].push_back(pid[i]); queue<int> q; q.push(kill); vector<int> res; while(!q.empty()){ int cur = q.front() res.push(cur); q.pop(); for(int i=0;i<map[cur].size();i++){ q.push(map[cur][i]); } } return res; }
【例子2】 打印杨辉三角形
杨辉三角形:(a+b)的n次方的系数。
思路:由于杨辉三角形中,下一行的系数能够依据前一行得到,所以,将前一行的系数放入队列中,在逐个出队列的时候,打印,同时将下一行的系数放在队列末尾。当前一行的系数已经全部出队列(打印完毕)之后,这时候下一行的所有系数刚好完全在队列当中。需要注意的是,为了方便计算,需要在每一层队列的最后都加上0,即.....1+0=1,得到下一层的最后一个数字1。打印时,将0忽略即可。
这里的思路其实就是BFS。同样的还有层序遍历二叉树。
代码:
#include <queue> #include<iostream> using namespace std; void printYangHui(int n){ queue<int> q; q.push(1); int cnt = 0; while(cnt<n){ int last = 0,cur; q.push(0); int len = q.size(); for(int i=0;i<len;i++){ cur = q.front(); if(cur)cout << cur << " "; q.pop(); q.push(last + cur); last = cur; } cout << endl; cnt ++; } } int main(){ printYangHui(5); return 0; }
【例子3】
以上是关于LeetCode 582. Kill Process 解题报告的主要内容,如果未能解决你的问题,请参考以下文章