LeetCode 2643.一最多的行:模拟(更新答案)
【LetMeFly】2643.一最多的行:模拟(更新答案)
力扣题目链接:https://leetcode.cn/problems/row-with-maximum-ones/
给你一个大小为 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]
为0
或1
解题方法:模拟
使用一个变量 m x mx mx记录当前一行中的最多1的个数,使用 a n s ans ans记录第一个有 m x mx mx个1的行的下标。
遍历每一行,统计每一行的1的个数。如果这一行的1的个数比mx多,就更新mx和ans。
最终返回{ans, mx}
。
- 时间复杂度 O ( m n ) O(mn) O(mn)
- 空间复杂度 O ( 1 ) O(1) O(1)
AC代码
C++
/*
* @Author: LetMeFly
* @Date: 2025-03-22 22:42:28
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-03-22 22:43:30
*/
class Solution {
public:
vector<int> rowAndMaximumOnes(vector<vector<int>>& mat) {
int mx = 0, ans = 0;
for (int i = 0; i < mat.size(); i++) {
int cnt = 0;
for (int j = 0; j < mat[i].size(); j++) {
cnt += mat[i][j];
}
if (cnt > mx) {
mx = cnt;
ans = i;
}
}
return {ans, mx};
}
};
Python
'''
Author: LetMeFly
Date: 2025-03-22 22:44:18
LastEditors: LetMeFly.xyz
LastEditTime: 2025-03-22 22:44:32
'''
from typing import List
class Solution:
def rowAndMaximumOnes(self, mat: List[List[int]]) -> List[int]:
mx, ans = 0, 0
for i in range(len(mat)):
cnt = sum(mat[i])
if cnt > mx:
mx, ans = cnt, i
return [ans, mx]
Java
/*
* @Author: LetMeFly
* @Date: 2025-03-22 22:49:36
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-03-22 22:50:36
*/
class Solution {
public int[] rowAndMaximumOnes(int[][] mat) {
int ans = 0, mx = 0;
for (int i = 0; i < mat.length; i++) {
int cnt = 0;
for (int j = 0; j < mat[i].length; j++) {
cnt += mat[i][j];
}
if (cnt > mx) {
mx = cnt;
ans = i;
}
}
return new int[]{ans, mx};
}
}
Go
/*
* @Author: LetMeFly
* @Date: 2025-03-22 22:51:01
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-03-22 22:52:04
*/
package main
func rowAndMaximumOnes(mat [][]int) []int {
ans, mx := 0, 0
for i := range mat {
cnt := 0
for _, t := range mat[i] {
cnt += t
}
if cnt > mx {
ans, mx = i, cnt
}
}
return []int{ans, mx}
}
同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~
千篇源码题解已开源