LeetCode每日一题,2025-08-21

全0子数组

重点是每次加上i-last,i是最右边的0的位置,左边可选的位置为[last+1,last+2,...i]i-last

java 复制代码
class Solution {
    public long zeroFilledSubarray(int[] nums) {
        long ans = 0;
        int last = -1;
        for (int i = 0; i < nums.length; i++) {
            int x = nums[i];
            if (x != 0) {
                last = i; // 记录上一个非 0 元素的位置
            } else {
                ans += i - last;
            }
        }
        return ans;
    }
}

统计全为1的正方形矩阵

这题重点是枚举上下两个边界,确定了边界,就确定了边长。然后题目变成了,统计有多少长度为h的全h子数组

java 复制代码
class Solution {
    public int countSquares(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        int ans = 0;
        for (int top = 0; top < m; top++) { // 枚举上边界
            int[] a = new int[n];
            for (int bottom = top; bottom < m; bottom++) { // 枚举下边界
                int h = bottom - top + 1; // 高
                // 2348. 全 h 子数组的数目
                int last = -1;
                for (int j = 0; j < n; j++) {
                    a[j] += matrix[bottom][j]; // 把 bottom 这一行的值加到 a 中
                    if (a[j] != h) {
                        last = j; // 记录上一个非 h 元素的位置
                    } else if (j - last >= h) { // 右端点为 j 的长为 h 的子数组全是 h
                        ans++;
                    }
                }
            }
        }
        return ans;
    }
}

提取出来, T 2348. 全 h 子数组的数目

java 复制代码
int last = -1;
for (int j = 0; j < n; j++) {
    a[j] += matrix[bottom][j]; // 把 bottom 这一行的值加到 a 中
    if (a[j] != h) {
        last = j; // 记录上一个非 h 元素的位置
    } else if (j - last >= h) { // 右端点为 j 的长为 h 的子数组全是 h
        ans++;
    }
}

统计全1子矩形

这个比上一题简单,确定了高度h以后,再加一个第一题就可以了

java 复制代码
class Solution {
    public int numSubmat(int[][] mat) {
        int m = mat.length;
        int n = mat[0].length;
        int ans = 0;
        for (int top = 0; top < m; top++) { // 枚举上边界
            int[] a = new int[n];
            for (int bottom = top; bottom < m; bottom++) { // 枚举下边界
                int h = bottom - top + 1; // 高
                // 2348. 全 h 子数组的数目
                int last = -1;
                for (int j = 0; j < n; j++) {
                    a[j] += mat[bottom][j]; // 把 bottom 这一行的值加到 a 中
                    if (a[j] != h) {
                        last = j; // 记录上一个非 h 元素的位置
                    } else {
                        ans += j - last;
                    }
                }
            }
        }
        return ans;
    }
}
相关推荐
Korloa8 分钟前
表达式(CSP-J 2021-Expr)题目详解
c语言·开发语言·数据结构·c++·算法·蓝桥杯·个人开发
手握风云-12 分钟前
回溯剪枝的 “减法艺术”:化解超时危机的 “救命稻草”(一)
算法·机器学习·剪枝
屁股割了还要学1 小时前
【数据结构入门】排序算法:插入排序
c语言·开发语言·数据结构·算法·青少年编程·排序算法
农场主John1 小时前
(栈)Leetcode155最小栈+739每日温度
windows·python·算法·leetcode·
MicroTech20251 小时前
微算法科技(NASDAQ: MLGO)研究分片技术:重塑区块链可扩展性新范式
算法·区块链
小五1271 小时前
机器学习聚类算法
算法·机器学习·聚类
艾莉丝努力练剑2 小时前
【C语言16天强化训练】从基础入门到进阶:Day 5
c语言·c++·学习·算法
尤超宇2 小时前
基于随机森林的红酒分类与特征重要性分析
算法·随机森林·分类
花火|2 小时前
算法训练营day58 图论⑧ 拓扑排序精讲、dijkstra(朴素版)精讲
算法·图论