一最多的行
难度:
标签:
题目描述
Given a m x n
binary matrix mat
, find the 0-indexed position of the row that contains the maximum count of ones, and the number of ones in that row.
In case there are multiple rows that have the maximum count of ones, the row with the smallest row number should be selected.
Return an array containing the index of the row, and the number of ones in it.
Example 1:
Input: mat = [[0,1],[1,0]]
Output: [0,1]
Explanation: Both rows have the same number of 1's. So we return the index of the smaller row, 0, and the maximum count of ones (1)
. So, the answer is [0,1].
Example 2:
Input: mat = [[0,0,0],[0,1,1]] Output: [1,2] Explanation: The row indexed 1 has the maximum count of ones(2)
. So we return its index,1
, and the count. So, the answer is [1,2].
Example 3:
Input: mat = [[0,0],[1,1],[0,0]] Output: [1,2] Explanation: The row indexed 1 has the maximum count of ones (2). So the answer is [1,2].
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 100
mat[i][j]
is either0
or1
.
代码结果
运行时间: 32 ms, 内存: 16.5 MB
/*
* 题目思路:
* 使用Java Stream API来简化代码,通过流的操作计算每一行中1的数量,找出包含最多1的行的下标和1的数量。
*/
import java.util.*;
import java.util.stream.*;
public class Solution {
public int[] findMaxOnesRow(int[][] mat) {
return IntStream.range(0, mat.length)
.mapToObj(i -> new int[]{i, (int) Arrays.stream(mat[i]).filter(x -> x == 1).count()})
.max(Comparator.comparingInt(a -> a[1]))
.orElse(new int[]{-1, 0});
}
}
解释
方法:
题解的核心思想是遍历矩阵的每一行,计算每行中1的数量,同时跟踪记录最大1的数量及其对应的行索引。如果发现有行1的数量大于当前记录的最大数量,则更新最大数量和行索引。最后返回包含最大1数量的行的索引和1的数量。这种方法直接遍历矩阵,计算每行的1的总数,并实时更新最大值和对应的行索引。
时间复杂度:
O(m * n)
空间复杂度:
O(1)
代码细节讲解
🦆
为什么这个算法选择遍历整个矩阵来计算每一行的1的数量,而不是使用更高效的方法,比如二分查找,尤其是在行已经排序的情况下?
▷🦆
如果矩阵中的每一行的长度不相同,这个算法还能否工作?需要做哪些调整来适应这种情况?
▷🦆
在比较行中1的数量时,如果有多行1的数量相同,算法是如何确保返回最小的行索引的?这部分逻辑在代码中是如何实现的?
▷🦆
当前算法在处理包含大量0的稀疏矩阵时的性能如何?是否有针对稀疏矩阵优化的方法可以提高效率?
▷