[LeetCode] Kill Process 結束進程

 

Given n processes, each process has a unique PID (process id) and its PPID (parent process id).html

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.post

Example 1:ui

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:this

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

 

這道題讓咱們結束進程,一直不想翻譯程殺死進程,感受進程很可憐的樣子,還要被殺死。題目給了咱們兩個數組,一個是進程的數組,還有一個是進程數組中的每一個進程的父進程組成的數組。題目中說結束了某一個進程,其全部的子進程都須要結束,因爲一個進程可能有多個子進程,因此咱們首先要理清父子進程的關係。因此咱們使用一個哈希表,創建進程和其全部子進程之間的映射,而後咱們首先把要結束的進程放入一個隊列queue中,而後while循環,每次取出一個進程,將其加入結果res中,而後遍歷其全部子進程,將全部子進程都排入隊列中,這樣咱們就能結束全部相關的進程,參見代碼以下:url

 

解法一:spa

class Solution {
public:
    vector<int> killProcess(vector<int>& pid, vector<int>& ppid, int kill) {
        vector<int> res;
        queue<int> q{{kill}};
        unordered_map<int, vector<int>> m;
        for (int i = 0; i < pid.size(); ++i) {
            m[ppid[i]].push_back(pid[i]);
        }
        while (!q.empty()) {
            int t = q.front(); q.pop();
            res.push_back(t);
            for (int p : m[t]) {
                q.push(p);
            }
        }
        return res;
    }
};

 

咱們也能夠使用遞歸的寫法,思路都同樣,只不過用遞歸函數來代替隊列,參見代碼以下:翻譯

 

解法二:code

class Solution {
public:
    vector<int> killProcess(vector<int>& pid, vector<int>& ppid, int kill) {
        vector<int> res;
        unordered_map<int, vector<int>> m;
        for (int i = 0; i < pid.size(); ++i) {
            m[ppid[i]].push_back(pid[i]);
        }
        helper(kill, m, res);
        return res;
    }
    void helper(int kill, unordered_map<int, vector<int>>& m, vector<int>& res) {
        res.push_back(kill);
        for (int p : m[kill]) {
            helper(p, m, res);
        }
    }
};

 

參考資料:

https://discuss.leetcode.com/topic/89293/c-clean-code-2-solution-dfs-bfs

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索