【Lintcode】1903. Department Statistics

题目地址:

https://www.lintcode.com/problem/department-statistics/description

给定两个字符串列表 E E E F F F E E E里的字符串的格式是id + 姓名 + 部门名,之间以逗号空格隔开,代表某个员工的信息; F F F里的字符串个数是id1 + id2,也以逗号空格隔开,代表这两个id对应的员工是朋友关系(朋友关系不具有传递性,只有对称性)。问每个部门中有别的部门的人作为朋友的员工数量。题目保证id与员工一一对应。

开两个哈希表,一个存每个部门有哪些员工id,另一个存每个id属于哪个部门。存完之后,遍历数组 F F F,取出两个id,如果这两个id属于同一个部门则不计数,否则说明id1和id2各自有朋友与他不属于同一个部门,则做计数。这里要注意,计数的时候要将id存入哈希表,而不能做加一的计数,这样会重复计算。代码如下:

import java.util.*;

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, Set<Integer>> deptEmps = new HashMap<>();
        Map<Integer, String> idToDept = new HashMap<>();
        for (String employee : employees) {
    
    
            String[] split = employee.split(", ");
            String dept = split[2];
            int id = Integer.parseInt(split[0]);
            // 存一下每个部门有哪些人
            deptEmps.putIfAbsent(dept, new HashSet<>());
            deptEmps.get(dept).add(id);
            
            idToDept.put(id, dept);
        }
        
        Map<String, Set<Integer>> count = new HashMap<>();
        for (String friendship : friendships) {
    
    
            String[] split = friendship.split(", ");
            int id1 = Integer.parseInt(split[0]), id2 = Integer.parseInt(split[1]);
            String dept1 = idToDept.get(id1), dept2 = idToDept.get(id2);
            if (dept1.equals(dept2)) {
    
    
                continue;
            }
            
            // 做计数
            count.putIfAbsent(dept1, new HashSet<>());
            count.get(dept1).add(id1);
            count.putIfAbsent(dept2, new HashSet<>());
            count.get(dept2).add(id2);
        }
        
        List<String> res = new ArrayList<>();
        for (Map.Entry<String, Set<Integer>> entry : deptEmps.entrySet()) {
    
    
            String dept = entry.getKey();
            int total = entry.getValue().size(), num = count.getOrDefault(dept, new HashSet<>()).size();
            res.add(dept + ": " + num + " of " + total);
        }
        
        return res;
    }
}

时空复杂度 O ( s l E + l F ) O(sl_E+l_F) O(slE+lF) s s s E E E中最长字符串长度。

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/112617677
今日推荐