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;
}
}