欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

leetcode 690

程序员文章站 2022-05-21 08:11:45
...

通过阅读题目就可以知道,这道题是通过dfs or bfs。

将所有的员工都放入到Map中,Map的key为员工的ID,value为员工的具体信息。

bfs:(Java 1.8)

public int bfs(List<Employee> employees, int id) {
        Queue<Employee> queue = new LinkedList<>();
        Map<Integer, Employee> map = employees.stream().collect(
                Collectors.toMap(Employee::getId,
                        employee -> employee,
                        (o, o2) -> o));
        queue.offer(map.get(id));
        int importantSum = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i=0; i<size; i++) {
                Employee poll = queue.poll();
                importantSum += poll.importance;
                if (poll.subordinates.size() != 0) {
                    for (Integer sub : poll.subordinates) {
                        queue.offer(map.get(sub));
                    }
                }
            }
        }
        return importantSum;
    }

dfs:

public int dfs(List<Employee> employees, int id) {
        Map<Integer, Employee> map = new HashMap<>();
        for (Employee employee : employees) {
            map.put(employee.id, employee);
        }
        Employee employee = map.get(id);
        int sum = getDfsNum(map, id);

        return sum;
    }
    public int getDfsNum(Map<Integer, Employee> map, int k) {
        int sum = 0;
        sum += map.get(k).importance;
        if (map.get(k).subordinates.size() == 0) {
            return sum;
        } else {
            for (Integer sub : map.get(k).subordinates) {
                sum += getDfsNum(map, sub);
            }
        }
        return sum;
    }

根据答案修改之后:

public int dfs(List<Employee> employees, int id) {
        Map<Integer, Employee> map = new HashMap<>();
        for (Employee employee : employees) {
            map.put(employee.id, employee);
        }
        Employee employee = map.get(id);
        int sum = getDfsNum(map, id);

        return sum;
    }
    public int getDfsNum(Map<Integer, Employee> map, int k) {
        int sum = map.get(k).importance;;
        for (Integer sub : map.get(k).subordinates) {
            sum += getDfsNum(map, sub);
        }
        return sum;
    }