注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
具体题目在这位大佬的帖子里:https://www.1point3acres.com/bbs ... read&tid=672261
找了一下leetcode,发现里面的discuss的链接不work了。自己写了一个,应该是O(VE)的解法。具体思路就是每一个节点走两层BFS,看一下neighbor之间有哎哟有没有相连的。
上面题目帖子里的两个例子都能过。希望大家能一起讨论一下,如果有不对或者可以优化的地方希望大家能指教。谢谢
- public class Main {
-
- public static int getMinScore(int prod_nodes, int prod_edges, int[] froms, int[] tos) {
- Map<Integer, List<Integer>> graph = new HashMap<>();
- int n = froms.length;
- for (int i = 0; i < n; i++) {
- int from = froms[i];
- int to = tos[i];
- graph.putIfAbsent(from, new ArrayList<>());
- graph.get(from).add(to);
- graph.putIfAbsent(to, new ArrayList<>());
- graph.get(to).add(from);
- }
- int min = Integer.MAX_VALUE;
-
- for(int node : graph.keySet()) {
- if (graph.get(node).size() < 2) {
- continue;
- }
- List<Integer> neighbors = graph.get(node);
- int node_e = neighbors.size();
- for (int nei : neighbors) {
- int nei_e = graph.get(nei).size();
- for (int nn : graph.get(nei)) {
- if (neighbors.contains(nn)) {
- int nn_e = graph.get(nn).size();
- int cur = (node_e - 2) + (nei_e - 2) + (nn_e - 2);
- min = Math.min(min, cur);
- }
- }
- }
- }
- return min == Integer.MAX_VALUE? -1 : min;
- }
-
-
-
- public static void main(String[] args) {
- int pn1 = 6;
- int pe1 = 6;
- int[] froms1 = new int[] {1,2,2,3,4,5};
- int[] tos1 = new int[] {2,4,5,5,5,6};
- System.out.println(getMinScore(pn1, pe1, froms1, tos1));
- int pn2 = 5;
- int pe2 = 6;
- int[] froms2 = new int[] {1,1,2,2,3,4};
- int[] tos2 = new int[] {2,3,3,4,4,5};
- System.out.println(getMinScore(pn2, pe2, froms2, tos2));
- }
- }
复制代码
|