leetcode6376. 一最多的行

给你一个大小为 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

#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;

vector<int> rowAndMaximumOnes(vector<vector<int>>& mat) {
	int m = mat.size();
	int n = mat[0].size();
	unordered_map<int, int> count;//记录出现次数
	int maxCount = 0;
	for (int i = 0; i < m; i++)
	{
		for (int j = 0; j < n; j++)
		{
			if (mat[i][j] == 1)
			{
				count[i]++;
			}
		}
		maxCount = max(maxCount, count[i]);//更新每一行出现次数最大值
	}
	int minIndex = INT_MAX;
	for (auto& e : count)
	{
		if (e.second == maxCount)
		{
			minIndex = min(minIndex, e.first);//更新最小的行号
		}
	}
	return { minIndex,maxCount };
}
int main() {
	vector<vector<int>> mat{ {0,1},{1,0} };
	vector<int> res = rowAndMaximumOnes(mat);
	for (int& e : res) {
		cout << e << " ";
	}
	cout << endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值