题目
1996. 游戏中弱角色的数量
你正在参加一个多角色游戏,每个角色都有两个主要属性:攻击 和 防御 。给你一个二维整数数组 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
题解1
思路
- 按照attack降序,defence升序的规则排列
- 这样,若后面的defence小于前面的defence则说明产生一个弱角色
代码
from typing import List
class Solution:
def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:
res = 0
maxDefence = 0
properties.sort(key=lambda x: (-x[0], x[1]))
for i in properties:
if(i[1] < maxDefence):
res+=1
else:
maxDefence = i[1]
return res
复杂度
- 时间复杂度: O ( n log n ) O(n\log n) O(nlogn)
- 空间复杂度: O ( 1 ) O(1) O(1)
题解2
思路
- 按照attack升序,defence降序规则排序
- 遍历数组,并尝试从栈中找到“强角色”,存在则总数+1,并将该元素压入栈中
代码
from collections import deque
from typing import List
class Solution:
def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:
res = 0
s = deque()
properties.sort(key=lambda x: (x[0], -x[1]))
for i in properties:
while s and s[-1] < i[1]:
s.pop()
res +=1
s.append(i[1])
return res
复杂度
- 时间复杂度: O ( n log n ) O(n\log n) O(nlogn)
- 空间复杂度: O ( n ) O(n) O(n)