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;
    }
}
相关推荐
L_09071 小时前
【Algorithm】双指针算法与滑动窗口算法
c++·算法
小龙报1 小时前
《构建模块化思维---函数(下)》
c语言·开发语言·c++·算法·visualstudio·学习方法
影子鱼Alexios3 小时前
机器人、具身智能的起步——线性系统理论|【二】状态空间方程的解
算法·机器学习·机器人
Guan jie3 小时前
10.4作业
数据结构·算法
我搞slam4 小时前
赎金信--leetcode
算法·leetcode
xxxmmc4 小时前
Leetcode 100 The Same Tree
算法·leetcode·职场和发展
Asmalin4 小时前
【代码随想录day 32】 力扣 509.斐波那契数列
算法·leetcode·职场和发展
胖咕噜的稞达鸭4 小时前
算法入门:专题攻克主题一---双指针(1)移动零 复写零
c语言·开发语言·c++·算法
海琴烟Sunshine5 小时前
leetcode 35.搜索插入的位置 python
python·算法·leetcode
程序员-King.5 小时前
day85——区域和的检索(LeetCode-303)
算法·前缀和