Leetcode 582. 杀掉进程

208 阅读1分钟

题目连接

解题思路

本题属于抽象树的类型题,意思是通过已知条件自己创建树结构,然后再进行解题。
首先,声明一个tree变量,以int为键,以[]int为值;
然后,通过遍历ppid数组构造一个tree;
最后,通过kill找到树中对应的子节点,将结果返回

复杂度分析

因为本题是用来并列for循环,所以时间复杂度是O(n)。

示例代码

func killProcess(pid []int, ppid []int, kill int) []int {
   tree := make(map[int][]int)
   for i := 0; i < len(ppid); i++ {
      if _, ok := tree[ppid[i]]; !ok {
         tree[ppid[i]] = []int{}
      }
      tree[ppid[i]] = append(tree[ppid[i]], pid[i])
   }


   result := []int{kill}


   for i := 0; i < len(result); i++ {
      childs := tree[result[i]]
      result = append(result, childs...)
   }


   return result
}