1615. 最大网络秩
题目:
思路:
【1】计数枚举的方式
【2】贪心的方式,只选取出拥有边最多的节点和次多的节点进行计算
代码展示:
【1】计数枚举的方式
//时间18 ms 击败 26.27% //内存42.8 MB 击败 80.51% class Solution { public int maximalNetworkRank(int n, int[][] roads) { HashMap<Integer, HashSet<Integer>> map = new HashMap<>(); for (int i = 0; i < n; i++){ map.put(i,new HashSet<Integer>()); } for (int[] path : roads){ HashSet<Integer> tem1 = map.get(path[0]); tem1.add(path[1]); HashSet<Integer> tem2 = map.get(path[1]); tem2.add(path[0]); } // 进行枚举的方式,复杂度一下子到了O(N^2) int p = 0; for (int i = 0; i < n - 1; i++){ HashSet<Integer> tem1 = map.get(i); for (int j = i+1; j < n; j++){ HashSet<Integer> tem2 = map.get(j); if (tem1.contains(j)){ p = Math.max(p,tem1.size()+tem2.size()-1); }else { p = Math.max(p,tem1.size()+tem2.size()); } } } return p; } }
【2】贪心的方式,只选取出拥有边最多的节点和次多的节点进行计算(相当于在第一种的方法上进行了截枝)
//时间1 ms 击败 100% //内存43.5 MB 击败 11.86% class Solution { public int maximalNetworkRank(int n, int[][] roads) { int[] degrees = new int[n]; for (int[] road : roads) { ++degrees[road[0]]; ++degrees[road[1]]; } int max1 = 0, max2 = 0; for (int degree : degrees) { if (degree > max1) { max2 = max1; max1 = degree; } else if (degree > max2 && degree < max1) { max2 = degree; } } int count1 = 0, count2 = 0; for (int degree : degrees) { if (degree == max1) { ++count1; } if (degree == max2) { ++count2; } } if (count1 == 1) { int edgeCount = 0; for (int[] road : roads) { if (degrees[road[0]] == max1 && degrees[road[1]] == max2 || degrees[road[0]] == max2 && degrees[road[1]] == max1) { ++edgeCount; } } return edgeCount == count2 ? max1 + max2 - 1 : max1 + max2; } else { int edgeCount = 0, limit = count1 * (count1 - 1) / 2; for (int[] road : roads) { if (degrees[road[0]] == max1 && degrees[road[1]] == max1) { ++edgeCount; } } return edgeCount == limit ? max1 * 2 - 1 : max1 * 2; } } }