LeetCode-Range Addition II

本文介绍了一种算法问题,即给定一个初始化为0的m*n矩阵,通过一系列更新操作,计算矩阵中最大值元素的数量。操作由二维数组表示,每个操作包括两个整数a和b,意味着矩阵中特定范围的元素将增加1。文章详细解释了如何通过找到操作范围的最小值来高效解决此问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description:
Given an m * n matrix M initialized with all 0’s and several update operations.

Operations are represented by a 2D array, and each operation is represented by an array with two positive integers a and b, which means M[i][j] should be added by one for all 0 <= i < a and 0 <= j < b.

You need to count and return the number of maximum integers in the matrix after performing all the operations.

Example 1:

Input: 
m = 3, n = 3
operations = [[2,2],[3,3]]
Output: 4
Explanation: 
Initially, M = 
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]

After performing [2,2], M = 
[[1, 1, 0],
 [1, 1, 0],
 [0, 0, 0]]

After performing [3,3], M = 
[[2, 2, 1],
 [2, 2, 1],
 [1, 1, 1]]

So the maximum integer in M is 2, and there are four of it in M. So return 4.

Note:

  • The range of m and n is [1,40000].
  • The range of a is [1,m], and the range of b is [1,n].
  • The range of operations size won’t exceed 10,000.

题意:给定两个正整数m,n构造一个所有元素均为0的矩阵M,同时有一个操作矩阵,每行包括两个元素a和b,对构造的矩阵执行M[i][j] += 1(0<=i<a, 0<=j<b);要求计算,经过操作矩阵的操作后,矩阵M中最大值元素的数量;

解法:最简单的办法自然就是先构造初始矩阵,然后根据给定的操作矩阵计算最后的矩阵,最后再求最大值的个数;但是,我们看到对于操作矩阵中的两个元素a,b,我们对构造的矩阵操作的元素范围为[0,a-1][0,b-1],因此我们只需要求操作矩阵中的所有操作的最小值,那么这个范围内的元素每次都会被加1,因此,最后得到的值也是最大的;

Java
class Solution {
    public int maxCount(int m, int n, int[][] ops) {
        int row = m;
        int col = n;
        for (int[] op : ops) {
            int a = op[0];
            int b = op[1];
            if (a < row) row = a;
            if (b < col) col = b;
        }
        return row * col;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值