[LeetCode] The Number of Weak Characters in the Game

1996. The Number of Weak Characters in the Game

You are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense. You are given a 2D integer array properties where properties[i] = [attacki, defensei] represents the properties of the ith character in the game.

A character is said to be weak if any other character has both attack and defense levels strictly greater than this character’s attack and defense levels. More formally, a character i is said to be weak if there exists another character j where attackj > attacki and defensej > defensei.

Return the number of weak characters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int numberOfWeakCharacters(vector<vector<int>>& properties) {
map<int, multiset<int>> m;
int res(0);
for(auto& p : properties) {
m[p[0]].insert(p[1]);
}

multiset<int> less;
for(auto it = begin(m); it != end(m); it++) {
auto lowerBound = less.lower_bound(*it->second.rbegin());
if(lowerBound != begin(less)) {
res += distance(begin(less), lowerBound);
less.erase(begin(less), lowerBound);
}
less.insert(begin(it->second), end(it->second));
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/16/PS/LeetCode/the-number-of-weak-characters-in-the-game/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.