LeetCode 题解工作台
区间加法 II
给你一个 m x n 的矩阵 M 和一个操作数组 op 。矩阵初始化时所有的单元格都为 0 。 ops[i] = [ai, bi] 意味着当所有的 0 和 0 时, M[x][y] 应该加 1。 在 执行完所有操作后 ,计算并返回 矩阵中最大整数的个数 。 示例 1: 输入: m = 3, n = …
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·数学
答案摘要
我们注意到,所有操作子矩阵的交集就是最终的最大整数所在的子矩阵,并且每个操作子矩阵都是从左上角 $(0, 0)$ 开始的,因此,我们遍历所有操作子矩阵,求出行数和列数的最小值,最后返回这两个值的乘积即可。 注意,如果操作数组为空,那么矩阵中的最大整数个数就是 $m \times n$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个 m x n 的矩阵 M 和一个操作数组 op 。矩阵初始化时所有的单元格都为 0 。ops[i] = [ai, bi] 意味着当所有的 0 <= x < ai 和 0 <= y < bi 时, M[x][y] 应该加 1。
在 执行完所有操作后 ,计算并返回 矩阵中最大整数的个数 。
示例 1:

输入: m = 3, n = 3,ops = [[2,2],[3,3]] 输出: 4 解释: M 中最大的整数是 2, 而且 M 中有4个值为2的元素。因此返回 4。
示例 2:
输入: m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]] 输出: 4
示例 3:
输入: m = 3, n = 3, ops = [] 输出: 9
提示:
1 <= m, n <= 4 * 1040 <= ops.length <= 104ops[i].length == 21 <= ai <= m1 <= bi <= n
解题思路
方法一:脑筋急转弯
我们注意到,所有操作子矩阵的交集就是最终的最大整数所在的子矩阵,并且每个操作子矩阵都是从左上角 开始的,因此,我们遍历所有操作子矩阵,求出行数和列数的最小值,最后返回这两个值的乘积即可。
注意,如果操作数组为空,那么矩阵中的最大整数个数就是 。
时间复杂度 ,其中 是操作数组 的长度。空间复杂度 。
class Solution:
def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:
for a, b in ops:
m = min(m, a)
n = min(n, b)
return m * n
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(k) for scanning all operations to find the minimum ai and bi, where k = ops.length. Space complexity is O(1) as no additional matrix storage is needed. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate immediately identifies the overlap of all operations without full matrix simulation.
- question_mark
They recognize that only the minimum ai and bi determine the maximum value region.
- question_mark
They handle the empty ops edge case and large matrix sizes efficiently.
常见陷阱
外企场景- error
Attempting to simulate each increment in the full matrix, which is unnecessary and inefficient.
- error
Failing to handle an empty ops array, incorrectly returning zero instead of m * n.
- error
Mixing up row and column limits when computing the overlap rectangle, leading to wrong counts.
进阶变体
外企场景- arrow_right_alt
Return the sum of all maximum integers instead of the count, which involves similar overlap reasoning.
- arrow_right_alt
Operations allow decrements as well, requiring careful tracking of minimum and maximum overlaps.
- arrow_right_alt
Compute the maximum value itself instead of the count, combining overlap detection with cumulative increments.