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;
    }
}
posted @   Tianyiya  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示