Python 329ms itrative version w/o stack, C++ can do it as well


  • 0
    Z

    Python version

    class Solution(object):
        def killProcess(self, pid, ppid, kill):
            """
            :type pid: List[int]
            :type ppid: List[int]
            :type kill: int
            :rtype: List[int]
            """
            children = collections.defaultdict(list)
            for i in xrange(len(pid)):
                children[ppid[i]].append(pid[i])
            result = [kill]
            for p in result:
                result += children[p]
            return result
    
    # 166 / 166 test cases passed.
    # Status: Accepted
    # Runtime: 329 ms
    

    C++

    class Solution {
    public:
        vector<int> killProcess(vector<int>& pid, vector<int>& ppid, int kill) {
            map<int, vector<int>> T;
            for ( int i = 0, n = pid.size(); i < n; ++i ) {
                T[ppid[i]].push_back(pid[i]);
            }
            vector<int> K;
            K.push_back(kill);
            for ( int i = 0; i < K.size(); ++i ) {
                K.insert(K.end(), T[K[i]].begin(), T[K[i]].end());
            }
            return K;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.