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.
這道題看起來像是之前那道 Range Addition 的拓展,但是感覺實際上更簡單一些。每次在 ops 中給定我們一個橫縱坐標,將這個子矩形范圍內的數字全部自增1,讓我們求最大數字的個數。原數組初始化均為0,那么如果 ops 為空,沒有任何操作,那么直接返回 m*n 即可,我們可以用一個優先隊列來保存最大數字矩陣的橫縱坐標,我們可以通過舉些例子發現,只有最小數字組成的邊界中的數字才會被每次更新,所以我們想讓最小的數字到隊首,更優先隊列的排序機制是大的數字在隊首,所以我們對其取相反數,這樣我們最后取出兩個隊列的隊首數字相乘即為結果,參見代碼如下:
解法一:
class Solution { public: int maxCount(int m, int n, vector<vector<int>>& ops) { if (ops.empty() || ops[0].empty()) return m * n; priority_queue<int> r, c; for (auto op : ops) { r.push(-op[0]); c.push(-op[1]); } return r.top() * c.top(); } };
我們可以對空間進行優化,不使用優先隊列,而是每次用 ops 中的值來更新m和n,取其中較小值,這樣遍歷完成后,m和n就是最大數矩陣的邊界了,參見代碼如下:
解法二:
class Solution { public: int maxCount(int m, int n, vector<vector<int>>& ops) { for (auto op : ops) { m = min(m, op[0]); n = min(n, op[1]); } return m * n; } };
Github 同步地址:
類似題目:
參考資料:
https://leetcode.com/problems/range-addition-ii/
https://leetcode.com/problems/range-addition-ii/discuss/103595/Java-Solution-find-Min