前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >天池 在线编程 部门统计(哈希)

天池 在线编程 部门统计(哈希)

作者头像
Michael阿明
发布2021-09-06 10:37:41
3620
发布2021-09-06 10:37:41
举报
文章被收录于专栏:Michael阿明学习之路

1. 题目

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

代码语言:javascript
复制
所有的输入中逗号后都跟有一个空格,而且你的程序输出也要和样例格式相同。

返回的列表对顺序没有要求。

员工信息数量 N <= 50 条。

朋友关系的数量 M <= 1000 条。

员工ID都是100以内的数字。

部门数 K <= 20。
代码语言:javascript
复制
示例
输入:
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"

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

2. 解题

代码语言:javascript
复制
class Solution {
public:
    /**
     * @param employees: information of the employees
     * @param friendships: the friendships of employees
     * @return: return the statistics
     */
    vector<string> departmentStatistics(vector<string> &employees, vector<string> &friendships) {
        // write your code here.
        unordered_map<string, int> count;
        unordered_map<string, string> id_dep;
        for(auto& e : employees)
        {
            vector<string> t = split(e);
            id_dep[t[0]] = t[2];
            count[t[2]]++;
        }
        unordered_map<string, unordered_set<string>> p;
        for(auto& f : friendships)
        {
            vector<string> t = split(f);
            if(id_dep[t[0]] != id_dep[t[1]]) // 同一个部门的话,不能计算
            {   
                p[id_dep[t[0]]].insert(t[0]);
                p[id_dep[t[1]]].insert(t[1]);
            }
        }
        vector<string> ans;
        for(auto& ct : count)
        {
            int all = ct.second;
            string dep = ct.first;
            int num = p[dep].size();
            ans.push_back(dep + ": " + to_string(num) + " of " + to_string(all));
        }
        return ans;
    }
    vector<string> split(string& str)
    {
        vector<string> t;
        string s;
        for(auto c : str)
        {
            if(c ==',')
            {
                t.push_back(s);
                s = "";
            }
            else if(c != ' ')
                s.push_back(c);
        }
        t.push_back(s);
        return t;
    }
};
我的CSDN博客地址 https://michael.blog.csd
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/04/03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 题目
  • 2. 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档