LeetCode 题解工作台
元素和小于等于 k 的子矩阵的数目
给你一个下标从 0 开始的整数矩阵 grid 和一个整数 k 。 返回包含 grid 左上角元素、元素和小于或等于 k 的 子矩阵 的数目。 示例 1: 输入: grid = [[7,6,3],[6,6,1]], k = 18 输出: 4 解释: 如上图所示,只有 4 个子矩阵满足:包含 grid …
3
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数组·matrix
答案摘要
题目实际上求的是二维矩阵有多少个和小于等于 的前缀子矩阵。 二维前缀和的计算公式为:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·matrix 题型思路
题目描述
给你一个下标从 0 开始的整数矩阵 grid 和一个整数 k。
返回包含 grid 左上角元素、元素和小于或等于 k 的 子矩阵的数目。
示例 1:
输入:grid = [[7,6,3],[6,6,1]], k = 18 输出:4 解释:如上图所示,只有 4 个子矩阵满足:包含 grid 的左上角元素,并且元素和小于或等于 18 。
示例 2:
输入:grid = [[7,2,9],[1,5,0],[2,6,6]], k = 20 输出:6 解释:如上图所示,只有 6 个子矩阵满足:包含 grid 的左上角元素,并且元素和小于或等于 20 。
提示:
m == grid.lengthn == grid[i].length1 <= n, m <= 10000 <= grid[i][j] <= 10001 <= k <= 109
解题思路
方法一:二维前缀和
题目实际上求的是二维矩阵有多少个和小于等于 的前缀子矩阵。
二维前缀和的计算公式为:
时间复杂度 ,空间复杂度 。其中 和 分别是矩阵的行数和列数。
class Solution:
def countSubmatrices(self, grid: List[List[int]], k: int) -> int:
s = [[0] * (len(grid[0]) + 1) for _ in range(len(grid) + 1)]
ans = 0
for i, row in enumerate(grid, 1):
for j, x in enumerate(row, 1):
s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + x
ans += s[i][j] <= k
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on how many submatrices are considered and prefix sums are computed, potentially O(m _n) for building sums and O(m_ n) for counting. Space complexity is O(m*n) for the prefix sum matrix. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect questions about handling large matrices efficiently without brute-force scanning.
- question_mark
Watch for prompts about early termination or skipping unnecessary submatrices.
- question_mark
Be ready to explain prefix sum construction and submatrix sum calculation clearly.
常见陷阱
外企场景- error
Forgetting that every submatrix must include the top-left element, not just any submatrix.
- error
Not using prefix sums, leading to excessive time complexity and potential TLE.
- error
Incorrect indexing when computing submatrix sums from the prefix sum array.
进阶变体
外企场景- arrow_right_alt
Count submatrices with bottom-right element included instead of top-left, requiring reversed iteration.
- arrow_right_alt
Find submatrices with sum exactly equal to k, needing precise sum matching.
- arrow_right_alt
Limit submatrix size to fixed dimensions while still including top-left element.