-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy paththe-number-of-weak-characters-in-the-game.cpp
50 lines (48 loc) · 1.4 KB
/
the-number-of-weak-characters-in-the-game.cpp
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
46
47
48
49
50
// Time: O(nlogn)
// Space: O(1)
class Solution {
public:
int numberOfWeakCharacters(vector<vector<int>>& properties) {
sort(begin(properties), end(properties),
[](const auto& a, const auto& b) {
return a[0] == b[0] ? a[1] > b[1] : a[0] < b[0];
});
int result = 0, max_d = 0;
for (int i = size(properties) - 1; i >= 0; --i) {
if (properties[i][1] < max_d) {
++result;
}
max_d = max(max_d, properties[i][1]);
}
return result;
}
};
// Time: O(nlogn)
// Space: O(n)
// faster in sort by using more space
class Solution2 {
public:
int numberOfWeakCharacters(vector<vector<int>>& properties) {
unordered_map<int, vector<int>> lookup;
for (const auto& p : properties) {
lookup[p[0]].emplace_back(p[1]);
}
vector<int> sorted_as;
for (const auto& [a, _] : lookup) {
sorted_as.emplace_back(a);
}
sort(begin(sorted_as), end(sorted_as), greater<int>());
int result = 0, max_d = 0;
for (const auto& a : sorted_as) {
for (const auto& d : lookup[a]) {
if (d < max_d) {
++result;
}
}
for (const auto& d : lookup[a]) {
max_d = max(max_d, d);
}
}
return result;
}
};