题目:
Given an
m * n
matrixM
initialized with all0
's and several update operations.
Operations are represented by a 2D array, and each operation is represented by an array with two positive integersa
andb
, which meansM[i][j]
should be added by one for all0 <= 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 exceed10,000
.
解释:
每次对于 0 <= i < a and 0 <= j < b
范围内的数进行+1操作,求最终最大的数的个数。
暴力求解肯定是不可取的,可以知道的是最终最大的数字一定是集中在矩阵左上角的一个矩阵,最大的数字是每次操作都会+1的位置, 这些位置就是0 <=i<min_a and 0<=i<min_b
,所以个数就是min_a * min_b
。
python代码:
class Solution(object):
def maxCount(self, m, n, ops):
"""
:type m: int
:type n: int
:type ops: List[List[int]]
:rtype: int
"""
if not ops:
return m*n
else:
return min(op[0] for op in ops)*min(op[1] for op in ops)
c++代码:
class Solution {
public:
int maxCount(int m, int n, vector<vector<int>>& ops) {
if(ops.size()==0)
return m*n;
vector<int> ops1;
vector<int> ops2;
for (auto op:ops)
{
ops1.push_back(op[0]);
ops2.push_back(op[1]);
}
return (*min_element(ops1.begin(),ops1.end()))*(*min_element(ops2.begin(),ops2.end()));
}
};
总结:
写c++ 容器范围的时候,不要手抖写错了…不然容易报runtime error错