leetcode 游戏中弱角色的数量(C++、java、python)

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

如果存在一个其他角色的攻击和防御等级 都严格高于 该角色的攻击和防御等级,则认为该角色为 弱角色 。更正式地,如果认为角色 i 弱于 存在的另一个角色 j ,那么 attackj > attacki 且 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 <= properties.length <= 105
  • properties[i].length == 2
  • 1 <= attacki, defensei <= 105

C++

class Solution {
public:
    static bool cmp(vector<int>& a, vector<int>& b) {
        if(a[0]==b[0]) {
            return a[1]<b[1];
        } else {
            return a[0]>b[0];
        }
    }

    int numberOfWeakCharacters(vector<vector<int>>& p) {
        int n=p.size();
        sort(p.begin(),p.end(),cmp);
        int tmp=p[0][1];
        int res=0;
        for(int i=1;i<n;i++) {
            if(p[i][1]<tmp) {
                res++;
            } else {
                tmp=max(tmp,p[i][1]);
            }
        }
        return res;
    }
};

java

class Solution {
    public int numberOfWeakCharacters(int[][] p) {
        Arrays.sort(p, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if (o1[0] == o2[0]) {
                    return o1[1] - o2[1];
                } else {
                    return o2[0] - o1[0];
                }
            }
        });
        int n = p.length;
        int res = 0;
        int tmp = p[0][1];
        for (int i = 1; i < n; i++) {
            if (p[i][1] < tmp) {
                res++;
            } else {
                tmp = Math.max(tmp, p[i][1]);
            }
        }
        return res;
    }
}

python

class Solution:
    def numberOfWeakCharacters(self, p: List[List[int]]) -> int:
        n = len(p)
        p = sorted(p, key=lambda x: (-x[0], x[1]))
        res = 0
        tmp = p[0][1]
        for i in range(1, n):
            if p[i][1] < tmp:
                res += 1
            else:
                tmp = max(tmp, p[i][1])
        return res

猜你喜欢

转载自blog.csdn.net/qq_27060423/article/details/120124029
今日推荐