Skip to content

Commit 84a5316

Browse files
authored
Create the-number-of-weak-characters-in-the-game.cpp
1 parent 9093d5f commit 84a5316

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Time: O(nlogn)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int numberOfWeakCharacters(vector<vector<int>>& properties) {
7+
sort(begin(properties), end(properties),
8+
[](const auto& a, const auto& b) {
9+
return a[0] == b[0] ? a[1] > b[1] : a[0] < b[0];
10+
});
11+
int result = 0, max_d = 0;
12+
for (int i = size(properties) - 1; i >= 0; --i) {
13+
if (properties[i][1] < max_d) {
14+
++result;
15+
}
16+
max_d = max(max_d, properties[i][1]);
17+
}
18+
return result;
19+
}
20+
};
21+
22+
// Time: O(nlogn)
23+
// Space: O(n)
24+
// faster in sort by using more space
25+
class Solution2 {
26+
public:
27+
int numberOfWeakCharacters(vector<vector<int>>& properties) {
28+
unordered_map<int, vector<int>> lookup;
29+
for (const auto& p : properties) {
30+
lookup[p[0]].emplace_back(p[1]);
31+
}
32+
vector<int> sorted_as;
33+
for (const auto& [a, _] : lookup) {
34+
sorted_as.emplace_back(a);
35+
}
36+
sort(begin(sorted_as), end(sorted_as), greater<int>());
37+
int result = 0, max_d = 0;
38+
for (const auto& a : sorted_as) {
39+
for (const auto& d : lookup[a]) {
40+
if (d < max_d) {
41+
++result;
42+
}
43+
}
44+
for (const auto& d : lookup[a]) {
45+
max_d = max(max_d, d);
46+
}
47+
}
48+
return result;
49+
}
50+
};

0 commit comments

Comments
 (0)