1
+ // Runtime: 1534 ms (Top 45.54%) | Memory: 199 MB (Top 25.74%)
1
2
class Solution {
2
3
public:
3
4
map<pair<int , int >, int >edgeCount;
4
5
vector<int >degree;
5
-
6
+
6
7
vector<int > countPairsHelper (vector<int >&indegree, vector<int >&queries, int n){
7
8
vector<int >ans;
8
-
9
+
9
10
// for each query, time: O(2*n) for two pointer and O(uniqueEdgesCount)
10
- for (int query: queries){
11
- // two pointer
11
+ for (int query: queries){
12
+ // two pointer
12
13
int i = 0 , j = n-1 , total = 0 ;
13
14
while (i != j){
14
15
if (degree[i] + degree[j] > query){
@@ -23,8 +24,7 @@ class Solution {
23
24
total += (n-i-1 );
24
25
i++;
25
26
}
26
-
27
-
27
+
28
28
// remove the negative contribution of edgeCount from all the pairs so far counted
29
29
for (auto i: edgeCount){
30
30
int u = i.first .first , v = i.first .second , w = i.second ;
@@ -38,7 +38,7 @@ class Solution {
38
38
return ans;
39
39
}
40
40
vector<int > countPairs (int n, vector<vector<int >>& edges, vector<int >& queries) {
41
-
41
+
42
42
vector<int >indegree (n, 0 );
43
43
for (auto edge: edges){
44
44
int x = edge[0 ], y = edge[1 ];
@@ -49,11 +49,11 @@ class Solution {
49
49
indegree[u]++;
50
50
indegree[v]++;
51
51
}
52
-
52
+
53
53
for (int i = 0 ; i < n; ++i){
54
54
degree.push_back (indegree[i]);
55
55
}
56
56
sort (degree.begin (), degree.end ()); // sort degree to apply smart two pointer
57
57
return countPairsHelper (indegree, queries, n);
58
58
}
59
- };
59
+ };
0 commit comments