📣 Back to School开学季 - VIP通行证5折优惠!蓝莓、Offer多多同步优惠
查看: 1215| 回复: 0
跳转到指定楼层
上一主题 下一主题
收起左侧

[高频题] 亚麻OA最近一道高频新题 "购物模式"

🔗
zxue | 只看该作者 |倒序浏览
全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
具体题目在这位大佬的帖子里:https://www.1point3acres.com/bbs ... read&tid=672261
找了一下leetcode,发现里面的discuss的链接不work了。自己写了一个,应该是O(VE)的解法。具体思路就是每一个节点走两层BFS,看一下neighbor之间有哎哟有没有相连的。
上面题目帖子里的两个例子都能过。希望大家能一起讨论一下,如果有不对或者可以优化的地方希望大家能指教。谢谢
  1. public class Main {

  2.    
  3.     public static int getMinScore(int prod_nodes, int prod_edges, int[] froms, int[] tos) {
  4.         Map<Integer, List<Integer>> graph = new HashMap<>();
  5.         int n = froms.length;
  6.         for (int i = 0; i < n; i++) {
  7.             int from = froms[i];
  8.             int to = tos[i];
  9.             graph.putIfAbsent(from, new ArrayList<>());
  10.             graph.get(from).add(to);
  11.             graph.putIfAbsent(to, new ArrayList<>());
  12.             graph.get(to).add(from);
  13.         }
  14.         int min = Integer.MAX_VALUE;
  15.    
  16.         for(int node : graph.keySet()) {
  17.             if (graph.get(node).size() < 2) {
  18.                 continue;
  19.             }
  20.             List<Integer> neighbors = graph.get(node);
  21.             int node_e = neighbors.size();
  22.             for (int nei : neighbors) {
  23.                 int nei_e = graph.get(nei).size();
  24.                 for (int nn : graph.get(nei)) {
  25.                     if (neighbors.contains(nn)) {
  26.                         int nn_e = graph.get(nn).size();
  27.                         int cur = (node_e - 2) + (nei_e - 2) + (nn_e - 2);
  28.                         min = Math.min(min, cur);
  29.                     }
  30.                 }
  31.             }
  32.         }
  33.         return min == Integer.MAX_VALUE? -1 : min;
  34.     }
  35.    

  36.    
  37.     public static void main(String[] args) {
  38.         int pn1 = 6;
  39.         int pe1 = 6;
  40.         int[] froms1 = new int[] {1,2,2,3,4,5};
  41.         int[] tos1 = new int[] {2,4,5,5,5,6};
  42.         System.out.println(getMinScore(pn1, pe1, froms1, tos1));
  43.         int pn2 = 5;
  44.         int pe2 = 6;
  45.         int[] froms2 = new int[] {1,1,2,2,3,4};
  46.         int[] tos2 = new int[] {2,3,3,4,4,5};
  47.         System.out.println(getMinScore(pn2, pe2, froms2, tos2));
  48.     }
  49. }
复制代码



上一篇:SWE实习面试前,要把非SWE面经也刷了吗?求大佬指点。
下一篇:56题一个语法求解 list.toArray
您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表