C/C++教程

[LeetCode] 1996. The Number of Weak Characters in the Game

本文主要是介绍[LeetCode] 1996. The Number of Weak Characters in the Game,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

You are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense. You are given a 2D integer array properties where properties[i] = [attacki, defensei] represents the properties of the ith character in the game.

A character is said to be weak if any other character has both attack and defense levels strictly greater than this character's attack and defense levels. More formally, a character i is said to be weak if there exists another character j where attackj > attacki and defensej > defensei.

Return the number of weak characters.

Example 1:

Input: properties = [[5,5],[6,3],[3,6]]
Output: 0
Explanation: No character has strictly greater attack and defense than the other.

Example 2:

Input: properties = [[2,2],[3,3]]
Output: 1
Explanation: The first character is weak because the second character has a strictly greater attack and defense.

Example 3:

Input: properties = [[1,5],[10,4],[4,3]]
Output: 1
Explanation: The third character is weak because the second character has a strictly greater attack and defense.

Constraints:

  • 2 <= properties.length <= 105
  • properties[i].length == 2
  • 1 <= attacki, defensei <= 105

游戏中弱角色的数量。

你正在参加一个多角色游戏,每个角色都有两个主要属性:攻击 和 防御 。给你一个二维整数数组 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目给的是一个二维数组,表示每个角色的攻击和防御数值。弱角色的定义是如果有另一个角色的攻击值和防御值同时大于当前这个角色的话,当前这个角色就可以被定义为弱角色

暴力解是O(n^2)的复杂度,有点类似 two sum 那样对角色的数值进行两两比较。我这里提供一个类似单调栈的思路。因为 input 给的应该是乱序的,所以这里我先根据所有角色的攻击值从小到大排序。排序之后,如果后一个角色的防御值比当前角色的防御值大的话,就很好判断当前角色是否是一个弱角色了。排序之后我们开始遍历 input 数组,同时记录一下当前遍历到的最大的防御值是多少,记为 max。对于之后还未遍历的角色,只有他的防御值大于 max,才可以将当前角色定义为弱角色。

时间O(nlogn) - 排序

空间O(1)

Java实现

 1 class Solution {
 2     public int numberOfWeakCharacters(int[][] properties) {
 3         int len = properties.length;
 4         int count = 0;
 5         Arrays.sort(properties, (a, b) -> (b[0] == a[0]) ? (a[1] - b[1]) : (b[0] - a[0]));
 6         int max = 0;
 7         for (int i = 0; i < len; i++) {
 8             if (properties[i][1] < max) {
 9                 count++;
10             }
11             max = Math.max(max, properties[i][1]);
12         }
13         return count;
14     }
15 }

 

LeetCode 题目总结

这篇关于[LeetCode] 1996. The Number of Weak Characters in the Game的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!