leetcode
leetcode 2651 ~ 2700
区间加法 II

区间加法 II

难度:

标签:

题目描述

You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai and 0 <= y < bi.

Count and return the number of maximum integers in the matrix after performing all the operations.

 

Example 1:

Input: m = 3, n = 3, ops = [[2,2],[3,3]]
Output: 4
Explanation: The maximum integer in M is 2, and there are four of it in M. So return 4.

Example 2:

Input: 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]]
Output: 4

Example 3:

Input: m = 3, n = 3, ops = []
Output: 9

 

Constraints:

  • 1 <= m, n <= 4 * 104
  • 0 <= ops.length <= 104
  • ops[i].length == 2
  • 1 <= ai <= m
  • 1 <= bi <= n

代码结果

运行时间: 22 ms, 内存: 17.4 MB


/*
 * Using Java Stream API, the approach remains the same as the non-stream solution.
 * We will use streams to find the minimum of the first and second elements in the ops array.
 * The minimums will then be multiplied to get the count of the maximum integer.
 */

import java.util.Arrays;

public class Solution {
    public int maxCount(int m, int n, int[][] ops) {
        int minA = Arrays.stream(ops)
                        .mapToInt(op -> op[0])
                        .min()
                        .orElse(m);
        int minB = Arrays.stream(ops)
                        .mapToInt(op -> op[1])
                        .min()
                        .orElse(n);
        return minA * minB;
    }
}

解释

方法:

这个题解的思路是利用题目给定操作的特点来简化计算。根据题意,所有满足 0 <= x < ai 和 0 <= y < bi 的格子都会加 1。因此,经过所有操作后,最终矩阵中最大的整数一定出现在所有操作的交集区域内。我们只需要找出所有操作中最小的 ai 和最小的 bi,它们的乘积就是最大整数的个数。如果 ops 为空,说明没有任何操作,此时矩阵中所有元素都为0,最大整数的个数就是 m*n。

时间复杂度:

O(len(ops))

空间复杂度:

O(len(ops))

代码细节讲解

🦆
为什么算法在计算最小的 ai 和 bi 时,选择使用两个列表 L1 和 L2 来存储所有 ai 和 bi 的值,而不是在遍历过程中直接维护当前的最小值?
使用两个列表 L1 和 L2 来存储所有 ai 和 bi 的值可能是出于代码编写的简便性考虑。这种方式使得代码更为直观和易于理解,特别是对于那些刚开始学习算法的学生。然而,这种方法确实存在效率上的不足,因为它需要额外的空间来存储这些值,并且在获取最小值时需要遍历整个列表。直接在遍历过程中维护最小值(使用变量存储当前遇到的最小 ai 和 bi)会更加高效,因为它无需额外的存储空间,同时还能减少计算时间。
🦆
题解中提到如果 ops 数组为空,返回 m * n,但是否需要考虑 m 或 n 为 0 的特殊情况?如果 m 或 n 为 0,返回值应该是多少?
确实应该考虑 m 或 n 为 0 的情况。如果 m 或 n 任何一个为 0,那么矩阵的面积为 0(因为矩阵的一维或两维不存在实际的格子)。在这种情况下,无论进行多少次操作,矩阵中的整数最大数目都应该是 0,因为实际上不存在任何格子可以增加值。因此,如果 m 或 n 为 0,正确的返回值应该是 0。
🦆
在实现中,每次操作都将 ai 和 bi 添加到列表中,这在操作数很大时会不会影响性能?是否有更优的方法来处理这个问题?
将每次操作的 ai 和 bi 添加到列表中确实会在操作数很大时影响性能,主要是因为这种实现方式需要更多的内存并且在寻找最小值时增加了计算量。更优的方法是在遍历 ops 的过程中直接维护两个变量,分别记录遇到的最小 ai 和最小 bi。这样可以避免使用额外的存储空间,并且可以在遍历一次过程中直接得到结果,从而提高算法的效率和性能。

相关问题

区间加法

区间加法