1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| class Solution { public int[] countPairs(int n, int[][] edges, int[] queries) { int[] degree = new int[n + 1]; Map<Integer, Integer> cntE = new HashMap<>(); for (int[] e : edges) { int x = e[0], y = e[1]; if (x > y) { int tmp = x; x = y; y = tmp; } ++degree[x]; ++degree[y]; cntE.merge(x << 16 | y, 1, Integer::sum); }
int[] ans = new int[queries.length]; int[] sortedDegree = degree.clone(); Arrays.sort(sortedDegree); for (int j = 0; j < queries.length; ++j) { int q = queries[j]; int left = 1, right = n; while (left < right) { if (sortedDegree[left] + sortedDegree[right] <= q) { ++left; } else { ans[j] += right - left; --right; } } for (Map.Entry<Integer, Integer> e : cntE.entrySet()) { int k = e.getKey(), c = e.getValue(); int s = degree[k >> 16] + degree[k & 0xffff]; if (s > q && s - c <= q) { --ans[j]; } } } return ans; } }
|