-
题目
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.
-
题目大意&解题思路
这道题目的意思是给你一个m和n,构建一个m行n列的二维数组,数组的元素均为0,然后给你一个ops的二维数组,该二维数组的每一行代表一种操作,什么操作呢,就是以ops数组中的元素为位置,将构建的原数组这些位置的值加1,比如ops数组一行为[2,2],代表原数组2行2列的所有元素加1,当所有的ops操作完成后,返回原二维数组中最大的数的出现的次数。
开始的时候我还真的构建的m行n列数组,结果显示超过内存,立马从数学的角度推理。
其实要知道数组中最大的数出现的次数,其实就是看,ops数组中所有元素中行出现的最小值和列出现的最小值,因为最小值因为只有这些位置+1,而别的位置没有+1,自然这些位置的值最大,比如ops数组中有[0,0]那么自然的话,原数组(0,0)位置的值最大了。
所以只需要求得ops数组中的最小的行和最小的列,返回其乘积即可。
-
实现方法
int maxCount(int m, int n, vector<vector<int>>& ops) {
if( ops.size() == 0)
return m*n;
int min_a = ops[0][0];
int min_b = ops[0][1];
int a, b;
for( int i = 0; i < ops.size(); ++i )
{
a = ops[i][0];
b = ops[i][1];
min_a = a < min_a? a : min_a;
min_b = b < min_b? b : min_b;
}
return min_a*min_b;
}
-
实验结果