获取Manager java下的所有员工列表

时间:2018-02-12 16:53:23

标签: java algorithm recursion data-structures hierarchy

我想创建一个Java层次结构问题,我想获得在给定经理下工作的所有员工的列表。

我的第一行输入包含managerId,我需要为其获取所有员工列表。

从第二行开始,我将在指数0和随后的所有报告者中拥有managerid。例如:

  

输入:

     

2

     

1234

     

2567

     

589

     

输出

     

56789

public class Solution {
  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int toFind = scan.nextInt();
    scan.nextLine();

    while (scan.hasNext()) {
        String str = scan.nextLine();
        char[] arr = str.toCharArray();

        int managerId = Integer.parseInt(String.valueOf(arr[0]));

        for (int idx = 1; idx < arr.length; idx++) {
            Employee.addEmployee(new Employee(Integer.parseInt(String.valueOf(arr[idx])), managerId));
        }

    }

    System.out.println(Employee.getReporteeList(toFind));
}
}

class Employee {

private int employeeId;
private int managerId;
private static Set<Integer> reporteeList = new HashSet<Integer>();
public static Map<Integer, Employee> employeeMap = new HashMap<Integer, Employee>();

public Employee(int employeeId, int managerId) {
    this.employeeId = employeeId;
    this.managerId = managerId;
}

public static void addEmployee(Employee emp) {
    if (employeeMap.get(emp.managerId) == null) {
        emp.reporteeList.add(emp.employeeId);
        employeeMap.put(emp.managerId, emp);
    } else {
        employeeMap.get(emp.managerId).reporteeList.add(emp.employeeId);
    }
}

static Set getReporteeList(int toFind) {

    return employeeMap.get(toFind).reporteeList;
}

@Override
public String toString() {
    // TODO Auto-generated method stub
    return "" + employeeId;
}
}

请帮助上述代码中缺少的内容,以便我可以正确获取所有员工的列表。

1 个答案:

答案 0 :(得分:0)

我建议使用一个Map将经理ID的数据保存到报告者列表中。然后给定一个经理ID,可以通过查看每个直接报告者的相同地图来获得报告者列表。

Map<Integer, List<Integer>> managerToReportees = new HashMap<>();
//Code to construct it/insert into it.

public List<Integer> getReportees(Integer employeeId) {
    List<Integer> reportees = new ArrayList<>();
    if (managerToReportees.containsKey(employeeId)) { //If the employee is a manager
       reportees.addAll(managerToReportees.get(employeeId)); //add all direct reports
       for(Integer empId : managerToReportees.get(employeeId)) { //for each of the direct reports recursively get the reportees
          reportees.addAll(getReportees(empId));
       }
    }
    return reportees; //return list of reportees for the current employeeId
}