LeetCode Daily 18
2022-1-28 T.1996 游戏中弱角色的数量
题目描述:
你正在参加一个多角色游戏,每个角色都有两个主要属性:攻击 和 防御 。给你一个二维整数数组 properties ,其中 properties[i] = [attacki, defensei] 表示游戏中第 i 个角色的属性。 如果存在一个其他角色的攻击和防御等级 都严格高于 该角色的攻击和防御等级,则认为该角色为 弱角色 。更正式地,如果认为角色 i 弱于 存在的另一个角色 j ,那么 attackj > attacki 且 defensej > defensei 。 返回 弱角色 的数量。
示例:
输入:properties = [[1,5],[10,4],[4,3]] 输出:1 解释:第三个角色是弱角色,因为第二个角色的攻击和防御严格大于该角色。
思路:
降序排列好攻击力。不断比较防御力,更新最大防御力,相同攻击力时不比较不更新。
代码:
class Solution { public: int numberOfWeakCharacters(vector<vector<int>>& properties){ sort(properties.rbegin(), properties.rend()); //STL降序排列 int ans = 0, old_defense = 0, max_defense = properties[0][1]; for(int i = 1; i < properties.size(); i++){ int now_defense = properties[i][1]; if(properties[i][0] != properties[i - 1][0]) { old_defense = max_defense; } if(now_defense < old_defense){ ans++; } else { max_defense = max(max_defense, now_defense); } } return ans; } };

浙公网安备 33010602011771号