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:
int maxCount(int m, int n, vector<vector<int>>& ops)
1、这道题给定一个m行n列的矩阵,矩阵所有数值都是0。
还给定了操作,放在二维矩阵中,比如[[2,2],[3,3]]这种形式,代表两个操作。
第一个操作是对0<=i<2和0<=j<2的子矩阵所有元素都加1。矩阵变化为[[1,1,0],[1,1,0],[0,0,0]]。
第二个操作是对0<=i<3和0<=j<3的子矩阵所有元素都加1。矩阵变化为[[2,2,1],[2,2,1],[1,1,1]]。
最后返回矩阵中数值最大的元素有几个,上述矩阵数值最大为2,一共有4个,返回4,。
2、上述题目似乎要对矩阵进行一个又一个的操作,最后再进行统计。
但我们也可以不改变矩阵数值,直接返回最后有多少个最大数值的矩阵元素就好。矩阵初始化为0为我们提供了这样做的可能性。
我们只需统计出所有这些操作都改变了哪些元素,哪些元素在每一次操作中都会加1。
最后返回这些元素的个数就好了。
代码如下:
int maxCount(int m, int n, vector<vector<int>>& ops)
{
int s1=ops.size();
if(s1==0)//边界情况,操作的矩阵是空的
return m*n;
int a=ops[0][0],b=ops[0][1];
for(int i=1;i<s1;i++)//统计出所有操作都改变了前几行,都改变了前几列
{
a=min(a,ops[i][0]);
b=min(b,ops[i][1]);
}
return a*b;//最后返回改变的行数*列数
}
上述代码实测9ms,beats 99.52% of cpp submissions。