zoukankan      html  css  js  c++  java
  • 5864. 游戏中弱角色的数量 力扣周赛(中等) 贪心,想不明白,sort比较函数坑点

    5864. 游戏中弱角色的数量

    你正在参加一个多角色游戏,每个角色都有两个主要属性:攻击 和 防御 。给你一个二维整数数组 properties ,其中 properties[i] = [attacki, defensei] 表示游戏中第 i 个角色的属性。

    如果存在一个其他角色的攻击和防御等级 都严格高于 该角色的攻击和防御等级,则认为该角色为 弱角色 。更正式地,如果认为角色 i 弱于 存在的另一个角色 j ,那么 attackj > attacki 且 defensej > defensei 。    返回 弱角色 的数量。

    示例 1:

    输入:properties = [[5,5],[6,3],[3,6]]
    输出:0
    解释:不存在攻击和防御都严格高于其他角色的角色。

    题解:

    将角色按照攻击从大到小排序,攻击相同的按照防御从小到大排序。

    然后遍历数组,维护遍历过的角色的防御的最大值 max

    对于当前角色 A,如果 A 防御< max,那么说明前面存在 B防御 > A防御,且 B攻击 > A攻击,

    (根据排序规则,如果 B 攻击== A攻击 ,B 防御<= A防御,否则 B攻击>A攻击,因为攻击从大到小排序)。

    代码:

    class Solution {    
    public:
        static bool cmp(vector<int>& a,vector<int>& b) // 这里不用&,会tle,玄学
        {
            if(a[0]!=b[0]) return a[0]>b[0];
              else return a[1]<b[1];
        }
        int numberOfWeakCharacters(vector<vector<int>>& properties) {
        sort(properties.begin(),properties.end(),cmp);
        int res=0,yy=0;
        for(auto property:properties)
        {
            if(property[1]<yy)  res++;
            if(property[1]>yy)  yy=property[1];
        }  
        return res;
    
        }
    };
  • 相关阅读:
    (Ubuntu)下载及安装Genymosion模拟器并配置Android Studio
    ROS CMakeLists中target_link_libraries相对路径设置
    VS_C#快捷键
    一行代码实现各产品访问统计???[原创]
    PyCharm下载安装
    装饰模式(Decorator)
    Python之格式化输出
    python入门
    servlet--http接口简单的创建及调用
    Storm-jdbc-2讲 高级API及Trident
  • 原文地址:https://www.cnblogs.com/stepping/p/15229433.html
Copyright © 2011-2022 走看看