题解 | 隐匿社交网络

隐匿社交网络

https://www.nowcoder.com/practice/2870f9db6aeb4eb08fbd6460397f9bf4

    这个题目虽然标题是并查集,但是真的用并查集的话,会超时;因为数据太多了。需要用特定的思路去优化,比如不用数组的形式表是group,不维护group而只计数。下面的算法的特点就是

  1. 用一个long来表示一个group(天然编号)
  2. 只维护组内的成员个数,而不维护具体是哪些成员(这一点就很不想并查集中的parent数组)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int groups = in.nextInt();
        while (groups > 0) {
            int n = in.nextInt();
            long[] wight = new long[n];
            for (int i = 0; i < n; i++) {
                wight[i] = in.nextLong();
            }
            groups--;
            System.out.println(getMaxGroupSize(wight));
        }
    }

    public static int getMaxGroupSize(long[] weight) {
        // key就是group编号。value就是组成员数
        Map<Long, Integer> groupMap = new HashMap<>();
        for (long wight : weight) {
            int curGroupSize = 1;
            long newGroup = wight;
            Long[] groupArr = groupMap.keySet().toArray(new Long[0]);
            for (Long group : groupArr) {
                if ((group & wight) != 0) {
                    newGroup |= group; //合并成一个新组————位运算
                    groupMap.remove(group); // 删除旧组
                    curGroupSize += groupMap.get(group); //计算新组的成员数
                }
            }
            // 上面这个for循环,通过当前wight就串联了一个出来了一个新组newGroup,并消灭了一下旧组,
            // 最后把新组放到map中
            groupMap.put(newGroup, curGroupSize);
        }
        int max = 1;
        for (Integer size : groupMap.values()) {
            max = Math.max(max, size);
        }
        return max;
    }
}

#面试紧张时你会有什么表现?##网申一定要掌握的小技巧##面试中,你被问过哪些奇葩问题?#
常规算法题目专栏 文章被收录于专栏

这里记录一些常规的算法题目题解,主要包括中等难度,还有一些有意思的题目~

全部评论
你抄的吧
点赞 回复 分享
发布于 04-07 20:20 上海

相关推荐

最喜欢秋天的火龙果很...:第一份工作一定要往大的去,工资低点没事。后面换工作会更好找,即使你去小公司,你也不可能不会换工作的。所以找大的去
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务