LeetCode 题解工作台

一最多的行

给你一个大小为 m x n 的二进制矩阵 mat ,请你找出包含最多 1 的行的下标(从 0 开始)以及这一行中 1 的数目。 如果有多行包含最多的 1 ,只需要选择 行下标最小 的那一行。 返回一个由行下标和该行中 1 的数量组成的数组。 示例 1: 输入: mat = [[0,1],[1,0]]…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·matrix

bolt

答案摘要

我们初始化一个数组 $\textit{ans} = [0, 0]$,用于记录最多 的行的下标和 的数量。 然后遍历矩阵的每一行,对于每一行:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·matrix 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个大小为 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.length 
  • n == mat[i].length 
  • 1 <= m, n <= 100 
  • mat[i][j]01
lightbulb

解题思路

方法一:模拟

我们初始化一个数组 ans=[0,0]\textit{ans} = [0, 0],用于记录最多 11 的行的下标和 11 的数量。

然后遍历矩阵的每一行,对于每一行:

  • 计算该行 11 的数量 cnt\textit{cnt}(由于矩阵中只包含 0011,我们可以直接对该行求和);
  • 如果 ans[1]<cnt\textit{ans}[1] < \textit{cnt},则更新 ans=[i,cnt]\textit{ans} = [i, \textit{cnt}]

遍历结束后,返回 ans\textit{ans}

时间复杂度 O(m×n)O(m \times n),其中 mmnn 分别是矩阵的行数和列数。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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?

help

常见问题

外企场景

一最多的行题解:数组·matrix | LeetCode #2643 简单