LeetCode 题解工作台
矩阵中的和
给你一个下标从 0 开始的二维整数数组 nums 。一开始你的分数为 0 。你需要执行以下操作直到矩阵变为空: 矩阵中每一行选取最大的一个数,并删除它。如果一行中有多个最大的数,选择任意一个并删除。 在步骤 1 删除的所有数字中找到最大的一个数字,将它添加到你的 分数 中。 请你返回最后的 分数 。…
5
题型
6
代码语言
3
相关题
当前训练重点
中等 · 数组·排序
答案摘要
我们可以先遍历矩阵的每一行,将每一行排序。 接下来,遍历矩阵的每一列,找到每一列的最大值,将这些最大值相加即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路
题目描述
给你一个下标从 0 开始的二维整数数组 nums 。一开始你的分数为 0 。你需要执行以下操作直到矩阵变为空:
- 矩阵中每一行选取最大的一个数,并删除它。如果一行中有多个最大的数,选择任意一个并删除。
- 在步骤 1 删除的所有数字中找到最大的一个数字,将它添加到你的 分数 中。
请你返回最后的 分数 。
示例 1:
输入:nums = [[7,2,1],[6,4,2],[6,5,3],[3,2,1]] 输出:15 解释:第一步操作中,我们删除 7 ,6 ,6 和 3 ,将分数增加 7 。下一步操作中,删除 2 ,4 ,5 和 2 ,将分数增加 5 。最后删除 1 ,2 ,3 和 1 ,将分数增加 3 。所以总得分为 7 + 5 + 3 = 15 。
示例 2:
输入:nums = [[1]] 输出:1 解释:我们删除 1 并将分数增加 1 ,所以返回 1 。
提示:
1 <= nums.length <= 3001 <= nums[i].length <= 5000 <= nums[i][j] <= 103
解题思路
方法一:排序
我们可以先遍历矩阵的每一行,将每一行排序。
接下来,遍历矩阵的每一列,找到每一列的最大值,将这些最大值相加即可。
时间复杂度 ,空间复杂度 。其中 和 分别是矩阵的行数和列数。
class Solution:
def matrixSum(self, nums: List[List[int]]) -> int:
for row in nums:
row.sort()
return sum(map(max, zip(*nums)))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Focus on sorting rows efficiently before starting iterative removal.
- question_mark
Consider using a priority queue if the interviewer hints at optimizing repeated max searches.
- question_mark
Be ready to explain why row-wise sorting ensures the maximum score.
常见陷阱
外企场景- error
Forgetting to sort rows in descending order can lead to suboptimal score calculations.
- error
Ignoring empty rows when collecting maximums may cause index errors.
- error
Using nested loops to find the maximum in every iteration is inefficient for large matrices.
进阶变体
外企场景- arrow_right_alt
Compute the minimum score by always adding the minimum among removed row elements instead of the maximum.
- arrow_right_alt
Allow diagonal or column-wise removals instead of only row-wise, changing the iteration pattern.
- arrow_right_alt
Handle dynamic matrices where new rows can be appended during operations, requiring online maximum tracking.