这篇文章主要为大家介绍了JavaC++算法题解leetcode1582二进制矩阵特殊位置示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
题目要求
思路:模拟
- 直接按题意模拟,先算出每行每列中“111”的个数,然后判断统计行列值均为111的位置即可。
Java
class Solution {
public int numSpecial(int[][] mat) {
int n = mat.length, m = mat[0].length;
int res = 0;
int[] row = new int[n], col = new int[m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
row[i] += mat[i][j];
col[j] += mat[i][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (mat[i][j] == 1 && row[i] == 1 && col[j] == 1)
res++;
}
}
return res;
}
}
- 时间复杂度:O(m×n)
- 空间复杂度:O(m+n)
C++
class Solution {
public:
int numSpecial(vector<vector<int>>& mat) {
int n = mat.size(), m = mat[0].size();
int res = 0;
vector<int> row(n), col(m);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
row[i] += mat[i][j];
col[j] += mat[i][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (mat[i][j] == 1 && row[i] == 1 && col[j] == 1)
res++;
}
}
return res;
}
};
- 时间复杂度:O(m×n)
- 空间复杂度:O(m+n)
Rust
- 这里的迭代函数用得不是很熟练,参考了好多才勉强理解下来。
impl Solution {
pub fn num_special(mat: Vec<Vec<i32>>) -> i32 {
let row = mat.iter().map(|row| row.iter().sum::<i32>()).collect::<Vec<_>>();
let col = (0..mat[0].len()).map(|i| mat.iter().map(|col| col[i]).sum::<i32>()).collect::<Vec<_>>();
(0..mat.len()).fold(0, |res, i| res + (0..mat[i].len()).filter(|&j| mat[i][j] == 1 && row[i] == 1 &&col[j] == 1).count() as i32)
}
}
- 时间复杂度:O(m×n)
- 空间复杂度:O(m+n)
以上就是Java C++ 算法题解leetcode1582二进制矩阵特殊位置的详细内容,更多关于Java C++ 二进制矩阵特殊位置的资料请关注编程学习网其它相关文章!
沃梦达教程
本文标题为:Java C++ 算法题解leetcode1582二进制矩阵特殊位置
猜你喜欢
- ubuntu下C/C++获取剩余内存 2023-09-18
- C++ 数据结构超详细讲解顺序表 2023-03-25
- C语言手把手带你掌握带头双向循环链表 2023-04-03
- C语言qsort()函数的使用方法详解 2023-04-26
- 详解C语言中sizeof如何在自定义函数中正常工作 2023-04-09
- c++ const 成员函数,返回一个 const 指针.但是返回的指针是什么类型的 const? 2022-10-11
- Easyx实现扫雷游戏 2023-02-06
- 我应该为我的项目使用相对包含路径,还是将包含目录放在包含路径上? 2022-10-30
- C语言详解float类型在内存中的存储方式 2023-03-27
- Qt计时器使用方法详解 2023-05-30
