1996.游戏中弱角色的数量
题目描述
思路
排序+双指针
对于每个角色,需要判断是否存在一个攻击值和防御值都高于它的角色,从而确定该角色是否为弱角色。可以按攻击和防御从大到小排序后,遍历到当前的指针时。之前的角色攻击力都是大于等于自己的,只需要知道他们之中大于自己攻击力的最高的防御力,来确认自己是不是弱角色就行。
使用双指针,第一个指针维护当前遍历到的攻击力(之前最高的防御力),第二个指针遍历与第一个指针攻击力相同的角色的防御力,统计弱角色的个数。
Python实现
class Solution:
def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:
properties.sort(key=lambda x:(-x[0], -x[1]))
ans = max_defense = i = 0
n = len(properties)
while i < n:
j, cur_max, max_defense = i, max_defense, max(max_defense, properties[i][1])
while j < n and properties[j][0] == properties[i][0]:
if cur_max > properties[j][1]:
ans += 1
j += 1
i = j
return ans
Java实现
class Solution {
public int numberOfWeakCharacters(int[][] properties) {
Arrays.sort(properties, (a,b)->{return a[0] == b[0] ? b[1] - a[1] : b[0] - a[0];});
int ans = 0;
for(int i = 0, maxDefense = 0, n = properties.length; i < n;){
int j = i, cur = maxDefense;
maxDefense = Math.max(maxDefense, properties[i][1]);
for(; j < n && properties[j][0] == properties[i][0]; j++)
if(properties[j][1] < cur)
ans++;
i = j;
}
return ans;
}
}