LeetCode-Range Addition II
阿新 • • 發佈:2018-12-16
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;
}
}