1996. 游戏中弱角色的数量
你正在参加一个多角色游戏,每个角色都有两个主要属性:攻击 和 防御 。给你一个二维整数数组 properties ,其中 properties[i] = [attacki, defensei] 表示游戏中第 i 个角色的属性。
如果存在一个其他角色的攻击和防御等级 都严格高于 该角色的攻击和防御等级,则认为该角色为 弱角色 。更正式地,如果认为角色 i 弱于 存在的另一个角色 j ,那么 attackj > attacki 且 defensej > defensei 。
返回 弱角色 的数量。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/the-number-of-weak-characters-in-the-game
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
单调栈
import java.util.Arrays;
import java.util.Comparator;
import java.util.Deque;
import java.util.LinkedList;
class Solution {
public int numberOfWeakCharacters(int[][] properties) {
if (properties == null || properties.length < 2) {
return 0;
}
Arrays.sort(properties, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1[0] == o2[0]) {
return Integer.compare(o2[1], o1[1]);
}
return Integer.compare(o1[0], o2[0]);
}
});
Deque<int[]> stack = new LinkedList<>();
int ans = 0;
for (int i = properties.length - 1; i >= 0; --i) {
while (!stack.isEmpty() && stack.peek()[1] <= properties[i][1]) {
stack.pop();
}
ans += stack.isEmpty() ? 0 : 1;
stack.push(properties[i]);
}
return ans;
}
}
排序
import java.util.Arrays;
import java.util.Comparator;
import java.util.Deque;
import java.util.LinkedList;
class Solution {
public int numberOfWeakCharacters(int[][] properties) {
if (properties == null || properties.length < 2) {
return 0;
}
Arrays.sort(properties, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1[0] == o2[0]) {
return Integer.compare(o2[1], o1[1]);
}
return Integer.compare(o1[0], o2[0]);
}
});
int max = 0;
int ans = 0;
for (int i = properties.length - 1; i >= 0; --i) {
if (properties[i][1] < max) {
ans++;
}
max = Math.max(properties[i][1], max);
}
return ans;
}
}
心之所向,素履以往 生如逆旅,一苇以航