给你一个大小为 rows x cols 的矩阵 mat,其中 mat[i][j] 是 0 或 1,请返回 矩阵 mat 中特殊位置的数目 。
特殊位置 定义:如果 mat[i][j] == 1 并且第 i 行和第 j 列中的所有其他元素均为 0(行和列的下标均 从 0 开始 ),则位置 (i, j) 被称为特殊位置。
示例 1:
输入:mat = [[1,0,0],
[0,0,1],
[1,0,0]]
输出:1
解释:(1,2) 是一个特殊位置,因为 mat[1][2] == 1 且所处的行和列上所有其他元素都是 0
示例 2:
输入:mat = [[1,0,0],
[0,1,0],
[0,0,1]]
输出:3
解释:(0,0), (1,1) 和 (2,2) 都是特殊位置
示例 3:
输入:mat = [[0,0,0,1],
[1,0,0,0],
[0,1,1,0],
[0,0,0,0]]
输出:2
示例 4:
输入:mat = [[0,0,0,0,0],
[1,0,0,0,0],
[0,1,0,0,0],
[0,0,1,0,0],
[0,0,0,1,1]]
输出:3
rows == mat.length
cols == mat[i].length
1 <= rows, cols <= 100
mat[i][j] 是 0 或 1
暴力模拟,遍历mat数组,统计各行各列包含1的数量,然后再遍历一次mat数组,统计元素本身为1,且该行该列1的数量也为1的元素个数。
- class Solution {
- public int numSpecial(int[][] mat) {
- int m = mat.length;
- int n = mat[0].length;
- int [] row = new int[m]; //行
- int [] col = new int[n]; //列
- int res = 0;
-
- //遍历每一行,统计1的个数
- for(int i=0; i
- int num1 = 0;
- for(int j=0; j
- if(mat[i][j]==1) num1++;
- }
- row[i] = num1;
- }
-
- //遍历每一列,统计1的个数
- for(int i=0; i
- int num1 = 0;
- for(int j=0; j
- if(mat[j][i]==1) num1++;
- }
- col[i] = num1;
- }
-
- for(int i=0; i
- for(int j=0; j
- if(mat[i][j]==1 && row[i]==1 && col[j]==1){
- res++;
- }
- }
- }
-
- return res;
- }
- }
上述代码还可以进行优化,即统计各行各列1的数量时一次遍历即可。
- class Solution {
- public int numSpecial(int[][] mat) {
- int m = mat.length;
- int n = mat[0].length;
- int [] row = new int[m]; //行
- int [] col = new int[n]; //列
- int res = 0;
-
- for(int i=0; i
- for(int j=0; j
- if(mat[i][j]==1){
- row[i]++;
- col[j]++;
- }
- }
- }
-
- for(int i=0; i
- for(int j=0; j
- if(mat[i][j]==1 && row[i]==1 && col[j]==1){
- res++;
- }
- }
- }
-
- return res;
- }
- }
-
相关阅读:
【知识点随笔分析】我看看谁还不会用CURL命令
Node.js 入门教程 32 JavaScript 异步编程与回调
Quanto: PyTorch 量化工具包
c# sqlsugar,hisql,freesql orm框架全方位性能测试对比 sqlserver 性能测试
如何有效防止服务器被攻击?
ESP8266 做简单的仪器
从一次性销售到持续收益:低代码服务商的转型之路
C# 复制、移动、删除文件,获取文件信息
C++之make_unique、namespace、class类总结(二百四十二)
彻底搞懂kubernetes调度框架与插件
-
原文地址:https://blog.csdn.net/qq_40682833/article/details/126686675
-
最新文章
-
沪漂五周年了:我越来越迷茫了
Agentic Skill Routing 实战:别再把所有 Skill 塞进 AI Agent 上下文
MySQL-Seconds_behind_master的精度误差
[MAF预定义ChatClient中间件-03]CachingChatClient——利用缓存省钱省时间
AI的至暗历史:从万众期待到被政府撤资,AI的两次死亡徘徊
Agent OS :五种驯服不确定性的范式
PortSwigger SQL注入LAB11
数据库即时编译JIT
[Begin]AI Learn Data Day 0
深度学习进阶(二十七)现代 LLM 的核心架构设计其二:SwiGLU