Leetcode.1996 游戏中弱角色的数量

题目链接

Leetcode.1996 游戏中弱角色的数量 Rating : 1861

题目描述

你正在参加一个多角色游戏,每个角色都有两个主要属性:攻击防御 。给你一个二维整数数组 p r o p e r t i e s properties properties ,其中 p r o p e r t i e s [ i ] = [ a t t a c k i , d e f e n s e i ] properties[i] = [attacki, defensei] properties[i]=[attacki,defensei] 表示游戏中第 i 个角色的属性。

如果存在一个其他角色的攻击和防御等级 都严格高于 该角色的攻击和防御等级,则认为该角色为 弱角色 。更正式地,如果认为角色 i 弱于 存在的另一个角色 j ,那么 a t t a c k j > a t t a c k i attackj > attacki attackj>attacki d e f e n s e j > d e f e n s e i defensej > defensei defensej>defensei

返回 弱角色 的数量。

示例 1:

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

示例 2:

输入:properties = [[2,2],[3,3]]
输出:1
解释:第一个角色是弱角色,因为第二个角色的攻击和防御严格大于该角色。

示例 3:

输入:properties = [[1,5],[10,4],[4,3]]
输出:1
解释:第三个角色是弱角色,因为第二个角色的攻击和防御严格大于该角色。

提示:
  • 2 < = p r o p e r t i e s . l e n g t h < = 1 0 5 2 <= properties.length <= 10^5 2<=properties.length<=105
  • p r o p e r t i e s [ i ] . l e n g t h = = 2 properties[i].length == 2 properties[i].length==2
  • 1 < = a t t a c k i , d e f e n s e i < = 1 0 5 1 <= attacki, defensei <= 10^5 1<=attacki,defensei<=105

解法:排序 & 贪心

先按如下规则对 p r o p e r t i e s properties properties 进行排序:

  • 攻击不相等,就按照攻击 从小到大 排序;
  • 否则就按照防御 从大到小 排序;

m x mx mx 记录已经遍历过的最大防御值:

  • 如果 m x > d e f e n s e ( 当前防御值 ) mx > defense(当前防御值) mx>defense(当前防御值),说明之前存在一个角色 q q q 是 “强于” 当前角色 p p p的,所以当前角色 p p p 是弱角色,答案 a n s + 1 ans + 1 ans+1
  • 否则就更新 m x mx mx,即 m x = m a x { m x , d e f e n s e } mx = max \{ mx , defense \} mx=max{mx,defense}

时间复杂度: O ( n × l o g n ) O(n \times logn) O(n×logn)

C++代码:

class Solution {
public:
    int numberOfWeakCharacters(vector<vector<int>>& properties) {
        //按攻击从大到小排序
        //攻击相同 : 按防御从小到大排序
        sort(properties.begin() , properties.end(),[&](auto &a, auto &b){
            if(a[0] != b[0]) return a[0] > b[0];
            return a[1] < b[1];
        });

        int mx = -1 , ans = 0;
        for(auto &p:properties){
            int attack = p[0] , defense = p[1];
            //说明之前存在一个角色q 防御 高于当前角色p
            //因为是按照攻击从大到小排序的,所以 q 的攻击 也应该高于 p
            //所以当前角色 p 是弱角色,ans + 1
            if(mx > defense) ans++;
            //否则就更新最大防御
            else mx = max(mx,defense);
        }
        return ans;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值