LeetCode 题解工作台
一最多的行
给你一个大小为 m x n 的二进制矩阵 mat ,请你找出包含最多 1 的行的下标(从 0 开始)以及这一行中 1 的数目。 如果有多行包含最多的 1 ,只需要选择 行下标最小 的那一行。 返回一个由行下标和该行中 1 的数量组成的数组。 示例 1: 输入: mat = [[0,1],[1,0]]…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·matrix
答案摘要
我们初始化一个数组 $\textit{ans} = [0, 0]$,用于记录最多 的行的下标和 的数量。 然后遍历矩阵的每一行,对于每一行:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·matrix 题型思路
题目描述
给你一个大小为 m x n 的二进制矩阵 mat ,请你找出包含最多 1 的行的下标(从 0 开始)以及这一行中 1 的数目。
如果有多行包含最多的 1 ,只需要选择 行下标最小 的那一行。
返回一个由行下标和该行中 1 的数量组成的数组。
示例 1:
输入:mat = [[0,1],[1,0]] 输出:[0,1] 解释:两行中 1 的数量相同。所以返回下标最小的行,下标为 0 。该行 1 的数量为 1 。所以,答案为 [0,1] 。
示例 2:
输入:mat = [[0,0,0],[0,1,1]] 输出:[1,2] 解释:下标为 1 的行中 1 的数量最多。该行 1 的数量为 2 。所以,答案为 [1,2] 。
示例 3:
输入:mat = [[0,0],[1,1],[0,0]] 输出:[1,2] 解释:下标为 1 的行中 1 的数量最多。该行 1 的数量为 2 。所以,答案为 [1,2] 。
提示:
m == mat.lengthn == mat[i].length1 <= m, n <= 100mat[i][j]为0或1
解题思路
方法一:模拟
我们初始化一个数组 ,用于记录最多 的行的下标和 的数量。
然后遍历矩阵的每一行,对于每一行:
- 计算该行 的数量 (由于矩阵中只包含 和 ,我们可以直接对该行求和);
- 如果 ,则更新 。
遍历结束后,返回 。
时间复杂度 ,其中 和 分别是矩阵的行数和列数。空间复杂度 。
class Solution:
def rowAndMaximumOnes(self, mat: List[List[int]]) -> List[int]:
ans = [0, 0]
for i, row in enumerate(mat):
cnt = sum(row)
if ans[1] < cnt:
ans = [i, cnt]
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Tests the candidate's ability to work with matrix traversal and counting techniques.
- question_mark
Checks if the candidate can identify the smallest index in the case of multiple maximum counts.
- question_mark
Assesses how well the candidate manages efficiency for larger matrices.
常见陷阱
外企场景- error
Not handling cases with multiple rows having the same number of ones correctly.
- error
Failing to consider the matrix's size and making the solution inefficient for larger inputs.
- error
Incorrectly implementing the count of ones or missing edge cases, such as an empty row or no ones in a row.
进阶变体
外企场景- arrow_right_alt
What if the matrix has only zeros? The algorithm should still return a valid row, even if all counts are zero.
- arrow_right_alt
What if the matrix contains only one row or one column? Consider edge cases where the matrix is minimal.
- arrow_right_alt
If we wanted to find the row with the least number of ones instead, how would that change the solution?