LeetCode 题解工作台

区间加法 II

给你一个 m x n 的矩阵 M 和一个操作数组 op 。矩阵初始化时所有的单元格都为 0 。 ops[i] = [ai, bi] 意味着当所有的 0 和 0 时, M[x][y] 应该加 1。 在 执行完所有操作后 ,计算并返回 矩阵中最大整数的个数 。 示例 1: 输入: m = 3, n = …

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·数学

bolt

答案摘要

我们注意到,所有操作子矩阵的交集就是最终的最大整数所在的子矩阵,并且每个操作子矩阵都是从左上角 $(0, 0)$ 开始的,因此,我们遍历所有操作子矩阵,求出行数和列数的最小值,最后返回这两个值的乘积即可。 注意,如果操作数组为空,那么矩阵中的最大整数个数就是 $m \times n$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个 m x n 的矩阵 M 和一个操作数组 op 。矩阵初始化时所有的单元格都为 0ops[i] = [ai, bi] 意味着当所有的 0 <= x < ai0 <= 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 * 104
  • 0 <= ops.length <= 104
  • ops[i].length == 2
  • 1 <= ai <= m
  • 1 <= bi <= n
lightbulb

解题思路

方法一:脑筋急转弯

我们注意到,所有操作子矩阵的交集就是最终的最大整数所在的子矩阵,并且每个操作子矩阵都是从左上角 (0,0)(0, 0) 开始的,因此,我们遍历所有操作子矩阵,求出行数和列数的最小值,最后返回这两个值的乘积即可。

注意,如果操作数组为空,那么矩阵中的最大整数个数就是 m×nm \times n

时间复杂度 O(k)O(k),其中 kk 是操作数组 ops\textit{ops} 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
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
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

区间加法 II题解:数组·数学 | LeetCode #598 简单