1
- class Solution {
2
- public int [] countPairs (int n , int [][] edges , int [] queries ) {
3
- int [] cnt = new int [n ];
4
- Map <Integer , Integer > g = new HashMap <>();
5
- for (var e : edges ) {
6
- int a = e [0 ] - 1 , b = e [1 ] - 1 ;
7
- ++cnt [a ];
8
- ++cnt [b ];
9
- int k = Math .min (a , b ) * n + Math .max (a , b );
10
- g .put (k , g . getOrDefault ( k , 0 ) + 1 );
11
- }
12
- int [] s = cnt .clone ();
13
- Arrays .sort (s );
14
- int [] ans = new int [queries .length ];
15
- for (int i = 0 ; i < queries .length ; ++i ) {
16
- int t = queries [i ];
17
- for (int j = 0 ; j < n ; ++j ) {
18
- int x = s [j ];
19
- int k = search (s , t - x , j + 1 );
20
- ans [i ] += n - k ;
21
- }
22
- for (var e : g .entrySet ()) {
23
- int a = e .getKey () / n , b = e .getKey () % n ;
24
- int v = e .getValue ();
25
- if (cnt [a ] + cnt [b ] > t && cnt [a ] + cnt [b ] - v <= t ) {
26
- --ans [i ];
27
- }
28
- }
29
- }
30
- return ans ;
31
- }
32
-
33
- private int search (int [] arr , int x , int i ) {
34
- int left = i , right = arr .length ;
35
- while (left < right ) {
36
- int mid = (left + right ) >> 1 ;
37
- if (arr [mid ] > x ) {
38
- right = mid ;
39
- } else {
40
- left = mid + 1 ;
41
- }
42
- }
43
- return left ;
44
- }
1
+ class Solution {
2
+ public int [] countPairs (int n , int [][] edges , int [] queries ) {
3
+ int [] cnt = new int [n ];
4
+ Map <Integer , Integer > g = new HashMap <>();
5
+ for (var e : edges ) {
6
+ int a = e [0 ] - 1 , b = e [1 ] - 1 ;
7
+ ++cnt [a ];
8
+ ++cnt [b ];
9
+ int k = Math .min (a , b ) * n + Math .max (a , b );
10
+ g .merge (k , 1 , Integer :: sum );
11
+ }
12
+ int [] s = cnt .clone ();
13
+ Arrays .sort (s );
14
+ int [] ans = new int [queries .length ];
15
+ for (int i = 0 ; i < queries .length ; ++i ) {
16
+ int t = queries [i ];
17
+ for (int j = 0 ; j < n ; ++j ) {
18
+ int x = s [j ];
19
+ int k = search (s , t - x , j + 1 );
20
+ ans [i ] += n - k ;
21
+ }
22
+ for (var e : g .entrySet ()) {
23
+ int a = e .getKey () / n , b = e .getKey () % n ;
24
+ int v = e .getValue ();
25
+ if (cnt [a ] + cnt [b ] > t && cnt [a ] + cnt [b ] - v <= t ) {
26
+ --ans [i ];
27
+ }
28
+ }
29
+ }
30
+ return ans ;
31
+ }
32
+
33
+ private int search (int [] arr , int x , int i ) {
34
+ int left = i , right = arr .length ;
35
+ while (left < right ) {
36
+ int mid = (left + right ) >> 1 ;
37
+ if (arr [mid ] > x ) {
38
+ right = mid ;
39
+ } else {
40
+ left = mid + 1 ;
41
+ }
42
+ }
43
+ return left ;
44
+ }
45
45
}
0 commit comments