1.题目
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的全部初始化为0的矩阵M,和几个更新操作。操作表示为二维数组,每个操作被两个整数a和b所表示,表示对所有的 0 <= i < a 和 0 <= j < b, 都有M[i][j]加1.你需要返回在执行了所有的操作后,矩阵中最大数字的个数。
2.思路
这道题比较容易想到的思路就是,真正执行这些操作,然后遍历M,求出结果。但是会很复杂。
时间复杂度较低的方法是,遍历ops数组,而并不真的对M执行操作。
因为对于给定的a和b,它都是从0的位置开始的,所以每次都是接近0,0的元素被操作。我们要做的就是,找到被操作次数最多的元素,具体办法为,找到被操作最多次的行数,和列数,相乘。被操作最多的行数,即为ops[i][0]的最小值;操作最多的列数,为ops[i][1]的最小值。
3.算法
class Solution {
public int maxCount(int m, int n, int[][] ops) {
if(m==0||n==0)return 0;
if(ops.length==0)return m*n;
if(ops[0].length==0)return m*n;
int[] temp=new int[ops[0].length];
int res=1;
for(int j=0;j<ops[0].length;j++){
temp[j]=Integer.MAX_VALUE;
for(int i=0;i<ops.length;i++){
temp[j]=temp[j]<ops[i][j]?temp[j]:ops[i][j];
}
res*=temp[j];
}
return res;
}
}
4.总结
temp要初始化为Integer的最大值而不是最小值;res要初始化为1而不是0.