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;
    }
}
相关推荐
fengfuyao98536 分钟前
竞争性自适应重加权算法(CARS)的MATLAB实现
算法
散峰而望38 分钟前
C++数组(二)(算法竞赛)
开发语言·c++·算法·github
leoufung39 分钟前
LeetCode 92 反转链表 II 全流程详解
算法·leetcode·链表
wyhwust1 小时前
交换排序法&冒泡排序法& 选择排序法&插入排序的算法步骤
数据结构·算法·排序算法
利刃大大1 小时前
【动态规划:背包问题】完全平方数
c++·算法·动态规划·背包问题·完全背包
wyhwust2 小时前
数组----插入一个数到有序数列中
java·数据结构·算法
im_AMBER2 小时前
Leetcode 59 二分搜索
数据结构·笔记·学习·算法·leetcode
gihigo19982 小时前
基于MATLAB的IEEE 14节点系统牛顿-拉夫逊潮流算法实现
开发语言·算法·matlab
leoufung2 小时前
LeetCode 61. 旋转链表(Rotate List)题解与思路详解
leetcode·链表·list
甄心爱学习3 小时前
数据挖掘-聚类方法
人工智能·算法·机器学习