[LeetCode] Kill Process 結束進程


 

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:

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

 

這道題讓我們結束進程,一直不想翻譯程殺死進程,感覺進程很可憐的樣子,還要被殺死。題目給了我們兩個數組,一個是進程的數組,還有一個是進程數組中的每個進程的父進程組成的數組。題目中說結束了某一個進程,其所有的子進程都需要結束,由於一個進程可能有多個子進程,所以我們首先要理清父子進程的關系。所以我們使用一個哈希表,建立進程和其所有子進程之間的映射,然后我們首先把要結束的進程放入一個隊列queue中,然后while循環,每次取出一個進程,將其加入結果res中,然后遍歷其所有子進程,將所有子進程都排入隊列中,這樣我們就能結束所有相關的進程,參見代碼如下:

 

解法一:

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;
    }
};

 

我們也可以使用遞歸的寫法,思路都一樣,只不過用遞歸函數來代替隊列,參見代碼如下:

 

解法二:

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 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM