Skip to content

Commit 23329c8

Browse files
authored
Create count-unhappy-friends.cpp
1 parent 3f24507 commit 23329c8

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

C++/count-unhappy-friends.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Time: O(n^2)
2+
// Space: O(n^2)
3+
4+
class Solution {
5+
public:
6+
int unhappyFriends(int n, vector<vector<int>>& preferences, vector<vector<int>>& pairs) {
7+
vector<vector<int>> friends(n, vector<int>(n));
8+
for (int i = 0; i < size(preferences); ++i) {
9+
for (int j = 0; j < size(preferences[i]); ++j) {
10+
friends[i][preferences[i][j]] = j;
11+
}
12+
}
13+
vector<int> pairing(n);
14+
for (const auto &p : pairs) {
15+
pairing[p[0]] = p[1];
16+
pairing[p[1]] = p[0];
17+
}
18+
19+
int result = 0;
20+
for (int i = 0; i < size(friends); ++i) {
21+
for (int j = 0; j < size(friends[i]); ++j) {
22+
if (j == i || j == pairing[i]) {
23+
continue;
24+
}
25+
if (friends[i][j] < friends[i][pairing[i]] &&
26+
friends[j][i] < friends[j][pairing[j]]) {
27+
++result;
28+
break;
29+
}
30+
}
31+
}
32+
return result;
33+
}
34+
};

0 commit comments

Comments
 (0)