690. 员工的重要性

两种方法,第一种用的广度收索,第二种是哈希表

class Solution {
    public int getImportance(List<Employee> employees, int id) {
        Employee boss=new Employee();
        int imp=0;
        for(Employee e:employees)
        {
            if(e.id==id)
                boss=e;
        }
        employees.remove(boss);
        Stack<Employee>stack=new Stack<Employee>();
        stack.push(boss);
        while(!stack.isEmpty())
        {
            Employee p=stack.pop();
            imp+=p.importance;
            List<Integer>ids=p.subordinates;
            List<Employee>li=new ArrayList<Employee>();
            for(Employee e:employees)
            {
                if(ids.contains(e.id))
                {
                    stack.push(e);
                    li.add(e);
                }
            }
            employees.removeAll(li);
        }
        return imp;
    }
}
public class Solution{
    HashMap<Integer,Employee> map;
    public int getImportance(List<Employee> employees,int id){
         map = new HashMap<>();
         for(Employee e:employees)map.put(e.id,e);
         return helper(map.get(id));

    }

    public int helper(Employee em) {
        int res = em.importance;
        for (int sub : em.subordinates) {
            res += helper(map.get(sub));

        }
        return res;

    }



}

猜你喜欢

转载自blog.csdn.net/qq_33420835/article/details/81810647
今日推荐