【精】领扣LintCode算法问题答案:1903. 部门统计

    科技2022-08-04  153

    1903. 部门统计

    描述

    公司给你提供了所有员工的信息,包括其ID,姓名和所属部门。 以及他们之间的朋友关系,每个关系中由2个ID组成,如 “1, 2” 代表1号员工和2号员工是朋友。 朋友关系不具有传递性,即B、C都是A的朋友,但B和C不一定是朋友。 请计算每个部门中与其它部门的员工有朋友关系的员工个数。

    所有的输入中逗号后都跟有一个空格,而且你的程序输出也要和样例格式相同。返回的列表对顺序没有要求。员工信息数量 N <= 50 条。朋友关系的数量 M <= 1000 条。员工ID都是100以内的数字。部门数 K <= 20。

    说明

    样例中,Engineer的1号员工和HR的2号员工是朋友关系,3号员工和Business的4号员工是朋友关系,所以Engineer有2个人和其它部门有朋友关系,输出"Engineer: 2 of 3“。

    样例 1:

    输入: employees = [ "1, Bill, Engineer", "2, Joe, HR", "3, Sally, Engineer", "4, Richard, Business", "6, Tom, Engineer" ] friendships = [ "1, 2", "1, 3", "3, 4" ] 输出: "Engineer: 2 of 3" "HR: 1 of 1" "Business: 1 of 1"

    原题传送门


    文章目录

    1903. 部门统计描述说明样例 1: 分析题解最后说两句声明


    分析

    看结果的输出,可以分析出需要统计部门总人数和在别的部门有朋友的人数。

    题解

    public class Solution { /** * @param employees: information of the employees * @param friendships: the friendships of employees * @return: return the statistics */ public List<String> departmentStatistics(List<String> employees, List<String> friendships) { // write your code here. // 员工和部门映射表 Map<String, String> employeeMap = new HashMap<>(); // 部门详情 Map<String, Dept> deptInfos = new LinkedHashMap<>(); for (String row : employees) { String[] info = row.split(","); String id = info[0]; String dept = info[2].trim(); employeeMap.put(id, dept); Dept deptInfo = deptInfos.get(dept); if (deptInfo == null) { deptInfo = new Dept(dept); deptInfos.put(dept, deptInfo); } // 部门人数增加 deptInfo.addTotalCount(); } // 在别的部门有朋友的员工 Set<String> friendSet = new HashSet<>(); for (String friendship : friendships) { String[] info = friendship.split(","); String e1 = info[0]; String e2 = info[1].trim(); if (!employeeMap.get(e1).equals(employeeMap.get(e2))) { friendSet.add(e1); friendSet.add(e2); } } // 在别的部门有朋友的员工以部门纬度计数 for (String id : friendSet) { String dept = employeeMap.get(id); deptInfos.get(dept).addFriendCount(); } // 建造结果 List<String> ret = new ArrayList<>(); for (Dept dept : deptInfos.values()) { ret.add(dept.name + ": " + dept.friendCount + " of " + dept.totalCount); } return ret; } class Dept { private String name; private int friendCount; private int totalCount; public Dept(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getFriendCount() { return friendCount; } public void addFriendCount() { this.friendCount++; } public int getTotalCount() { return totalCount; } public void addTotalCount() { this.totalCount++; } } }

    最后说两句

    非常感谢你阅读本文章,如果你觉得本文对你有所帮助,请留下你的足迹,点个赞,留个言,多谢~

    作者水平有限,如果文章内容有不准确的地方,请指正。

    希望小伙伴们都能每天进步一点点。

    声明

    本文由二当家的白帽子博客原创,转载请注明来源,谢谢~

    Processed: 0.009, SQL: 8