题目原址
https://leetcode.com/problems/range-addition-ii/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,然后用参数ops二维数组去更新矩阵中的每个元素值,如a = 2, b = 2,则将矩阵中下标 [0][0] 、[0][1]、[1][0]、[1][1]
元素都加1,依次类推,在将矩阵中的所有元素操作完成后,要找到矩阵中最大元素的个数,并返回
这个题的解法不是很难,因为首先要找到最大的元素,那要考虑的问题就是,什么样的元素是最大的,肯定是被操作的次数最多的当然就是最大的,因为没操作一次就会增加1。所以问题就转变为,找给定的二维数组中重叠的行和列的个数,能够重叠的行和列当然就是所给的二维数组中第一列最小的值和第二列最小的值啦。所以所求的结果就是将这两个最小值相乘
所以为觉得,这类题,主要是考察理解题的能力,和题转换为数学模型的能力。
AC代码
class Solution {
public int maxCount(int m, int n, int[][] ops) {
for(int[] op: ops) {
m = Math.min(m,op[0]);
n = Math.min(n,op[1]);
}
return m * n;
}
}