【Leetcode】1582. Special Positions in a Binary Matrix

该博客介绍了一个LeetCode问题,目标是计算给定的0-1矩阵中,那些是所在行和列唯一1的个数。解决方案是首先统计每行和每列1的总数,然后遍历矩阵检查每个1是否是唯一的。时间复杂度为O(mn),空间复杂度为O(m+n)。
摘要由CSDN通过智能技术生成

题目地址:

https://leetcode.com/problems/special-positions-in-a-binary-matrix/

给定一个 m × n m\times n m×n 0 − 1 0-1 01矩阵,判断其有多少个 1 1 1满足其是它所在行和列里的唯一的 1 1 1

先统计每行和每列总共多少个 1 1 1,然后搜索所有的 1 1 1看它是否是本行、列里唯一的 1 1 1。代码如下:

public class Solution {
    public int numSpecial(int[][] mat) {
        int[] row1 = new int[mat.length], col1 = new int[mat[0].length];
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[0].length; j++) {
                if (mat[i][j] == 1) {
                    row1[i]++;
                    col1[j]++;
                }
            }
        }
        
        int res = 0;
        for (int i = 0; i < mat.length; i++) {
            if (row1[i] != 1) {
                continue;
            }
            
            for (int j = 0; j < mat[0].length; j++) {
                if (col1[j] != 1) {
                    continue;
                }
                
                if (mat[i][j] == 1) {
                    res++;
                }
            }
        }
        
        return res;
    }
}

时间复杂度 O ( m n ) O(mn) O(mn),空间 O ( m + n ) O(m+n) O(m+n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值