LeetCode 题解工作台
修改矩阵
给你一个下标从 0 开始、大小为 m x n 的整数矩阵 matrix ,新建一个下标从 0 开始、名为 answer 的矩阵。使 answer 与 matrix 相等,接着将其中每个值为 -1 的元素替换为所在列的 最大 元素。 返回矩阵 answer 。 示例 1: 输入: matrix = […
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·matrix
答案摘要
我们可以根据题目描述,遍历每一列,找到每一列的最大值,然后再遍历每一列,将值为 -1 的元素替换为该列的最大值。 时间复杂度 $O(m \times n)$,其中 和 分别是矩阵的行数和列数。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·matrix 题型思路
题目描述
给你一个下标从 0 开始、大小为 m x n 的整数矩阵 matrix ,新建一个下标从 0 开始、名为 answer 的矩阵。使 answer 与 matrix 相等,接着将其中每个值为 -1 的元素替换为所在列的 最大 元素。
返回矩阵 answer 。
示例 1:
输入:matrix = [[1,2,-1],[4,-1,6],[7,8,9]] 输出:[[1,2,9],[4,8,6],[7,8,9]] 解释:上图显示了发生替换的元素(蓝色区域)。 - 将单元格 [1][1] 中的值替换为列 1 中的最大值 8 。 - 将单元格 [0][2] 中的值替换为列 2 中的最大值 9 。
示例 2:
输入:matrix = [[3,-1],[5,2]] 输出:[[3,2],[5,2]] 解释:上图显示了发生替换的元素(蓝色区域)。
提示:
m == matrix.lengthn == matrix[i].length2 <= m, n <= 50-1 <= matrix[i][j] <= 100- 测试用例中生成的输入满足每列至少包含一个非负整数。
解题思路
方法一:模拟
我们可以根据题目描述,遍历每一列,找到每一列的最大值,然后再遍历每一列,将值为 -1 的元素替换为该列的最大值。
时间复杂度 ,其中 和 分别是矩阵的行数和列数。空间复杂度 。
class Solution:
def modifiedMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
m, n = len(matrix), len(matrix[0])
for j in range(n):
mx = max(matrix[i][j] for i in range(m))
for i in range(m):
if matrix[i][j] == -1:
matrix[i][j] = mx
return matrix
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(m*n) due to two full passes through the matrix. Space complexity is O(n) to store the maximum for each column. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can you precompute any values to avoid multiple scans of the matrix?
- question_mark
How would you handle matrices where multiple -1s appear in the same column?
- question_mark
Is there a way to do this without modifying the original matrix in place?
常见陷阱
外企场景- error
Scanning each -1 individually for its column maximum increases runtime unnecessarily.
- error
Modifying the original matrix before storing column maxima can overwrite needed data.
- error
Assuming every column may have only one -1 can lead to incorrect replacements.
进阶变体
外企场景- arrow_right_alt
Replace -1 with the minimum value in its row instead of column maxima.
- arrow_right_alt
Handle larger matrices where -1 can appear in multiple columns simultaneously.
- arrow_right_alt
Allow negative numbers to be valid maxima and adjust replacement logic accordingly.