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;
}
}
心之所向,素履以往 生如逆旅,一苇以航
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义