每日一题——LeetCode1582.二进制矩阵中的特殊位置

方法一 模拟

先把矩阵每一行和每一列中1的数量统计出来,然后遍历矩阵,元素为1的位置看他所在的行和列的1的数量是否都为1即为满足题意的点

javascript 复制代码
var numSpecial = function(mat) {
   let m = mat.length, n = mat[0].length
   let rows = new Array(m).fill(0)
   let cols = new Array(n).fill(0)
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            rows[i] += mat[i][j]
            cols[j] += mat[i][j]
        }
    }
    let res = 0
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (mat[i][j] === 1 && rows[i] === 1 && cols[j] === 1) {
                res++
            }
        }
    }
    return res
};

消耗时间和内存情况:

方法二 列的标记值

统计每一行1的频次,然后在第一行对应列加上这个频次,如果当前行是第一行,避免重复统计需要减1

作者:力扣官方题解

链接:leetcode.1582二进制矩阵中的特殊位置

javascript 复制代码
var numSpecial = function(mat) {
    const m = mat.length, n = mat[0].length;
    for (let i = 0; i < m; i++) {
        let cnt1 = 0;
        for (let j = 0; j < n; j++) {
            if (mat[i][j] === 1) {
                cnt1++;
            }
        }
        if (i === 0) {
            cnt1--;
        }
        if (cnt1 > 0) {
            for (let j = 0; j < n; j++) {
                if (mat[i][j] === 1) {
                    mat[0][j] += cnt1;
                }
            }
        }
    }
    let sum = 0;
    for (const num of mat[0]) {
        if (num === 1) {
            sum++;
        }
    }
    return sum;
};

消耗时间和内存情况:

相关推荐
Tiandaren23 分钟前
Selenium 4 教程:自动化 WebDriver 管理与 Cookie 提取 || 用于解决chromedriver版本不匹配问题
selenium·测试工具·算法·自动化
岁忧1 小时前
(LeetCode 面试经典 150 题 ) 11. 盛最多水的容器 (贪心+双指针)
java·c++·算法·leetcode·面试·go
chao_7891 小时前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
一斤代码2 小时前
vue3 下载图片(标签内容可转图)
前端·javascript·vue
3Katrina3 小时前
深入理解 useLayoutEffect:解决 UI "闪烁"问题的利器
前端·javascript·面试
秋说3 小时前
【PTA数据结构 | C语言版】一元多项式求导
c语言·数据结构·算法
coderlin_3 小时前
BI布局拖拽 (1) 深入react-gird-layout源码
android·javascript·react.js
Maybyy4 小时前
力扣61.旋转链表
算法·leetcode·链表
伍哥的传说4 小时前
React 实现五子棋人机对战小游戏
前端·javascript·react.js·前端框架·node.js·ecmascript·js
我在北京coding4 小时前
element el-table渲染二维对象数组
前端·javascript·vue.js